Regular Expression to match string starting with "stop"

Sean picture Sean · Aug 6, 2009 · Viewed 417k times · Source

How do I create a regular expression to match a word at the beginning of a string. We are looking to match stop at the beginning of a string and anything can follow it.

For example the expression should match:

stop
stop random
stopping

Thanks.

Answer

Vinko Vrsalovic picture Vinko Vrsalovic · Aug 6, 2009

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.)