Regular expression question 1

Regular expression question 1
0.0 0

#1

hey

can someone explain this expression. This expression is for finding keywords with 3 words like: i play football

The first thing i don’t understand is why it starts with looking for white space

^\s*[^\s]+(\s+[^\s]+){2}\s*$

#2

From left to right:

^                 # 1. start of string
\s*               # 2. zero or more spaces
[^\s]+            # 3. one or more characters that are not spaces -
                  #    this could/should have been `\S+`
(\s+[^\s]+){2}    # 4. two matching groups of the form:
                  #    one or more spaces, followed by one or more characters
                  #    that are not spaces. This could/should have been `(\s+\S+){2}`.
\s*               # 5. zero or more spaces
$                 # 6. end of string

It starts/ends looking for whitespace to take into account that the string could be like:

"          I      like      football           "

To my eyes it is a bit of a weird way to do things: it doesn’t really find three keywords, for example it will match on:

😀 😖 🤡

It looks for:

maybe some spaces
some characters that are not spaces
one or more spaces
some characters that are not spaces
one or more spaces
some characters that are not spaces
maybe some spaces

It could have been written as:

^\s*\S+\s+\S+\s+\S+\s*$

#3

thanks Dan! I am a bit green in regex and i had a hard time gather the different pieces.