Regular expression to match string starting with a specific word

If you wish to match only lines beginning with stop, use

^stop

If you wish to match lines beginning with the word stop followed by a space:

^stop\s

Or, if you wish to match lines beginning with the word stop, but followed by either a space or any other non-word character you can use (your regex flavor permitting)

^stop\W

On the other hand, what follows matches a word at the beginning of a string on most regex flavors (in these flavors \w matches the opposite of \W)

^\w

If your flavor does not have the \w shortcut, you can use

^[a-zA-Z0-9]+

Be wary that this second idiom will only match letters and numbers, no symbol whatsoever.

Check your regex flavor manual to know what shortcuts are allowed and what exactly do they match (and how do they deal with Unicode).

Leave a Comment