197

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

10 Answers10

314

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
  • 65
    +1 for generalizing your answer. I would love to see more of this on Stack Overflow. Makes it a better learning resource in my opinion. – Jim Aug 06 '09 at 18:26
  • How to make it case insensitive i.e. match Stop or stop or sTop? – Elton Santana Jun 19 '18 at 19:45
  • Depends on your language... Perl compatible can use the I modifier. /regex/i .NET RegexOptions.IgnoreCase and so on – Vinko Vrsalovic Jun 19 '18 at 19:49
  • 2
    Don't forget `^stop\b`, which would allow any boundary, including end of line – Mad Physicist Apr 07 '20 at 17:15
  • This is nice, but it does not work for my situation. I asked a question specific to my exact situation, but I was told that this one is a "similar" question. Unfortunately, it is not similar because the answers to this question do not address my specific requirement. So, what if I need a word (phrase) exactly like this `https://www.example.com/c/`? where anything can follow the c/ part, but the beginning must be as stated here. –  Feb 26 '21 at 04:09
  • Replace `stop` by `https://www.example.com/c/`? @DavidCovey – Vinko Vrsalovic Feb 26 '21 at 14:18
  • Thanks, I'll give that a shot, though I suspect I'll run into conflicts with some of the "special characters" my string uses such as `/` `:` and `.` –  Feb 27 '21 at 17:52
  • I finally played around enough to get it. Thanks for your help. It got me started in the right direction. I ended up with this: `^http:\/\/www\.example\.com\/c\/\b` to restrict the input to exactly `http://www.example.com/c/` with anything else following. –  Feb 28 '21 at 01:28
  • I tweaked it a bit to allow for optional `http/https` and `www/no www`. It works great like this: `https?:\/\/(www\.)?example\.com\/c\/\b` Thanks all. –  Feb 28 '21 at 02:27
  • Note of this worked, idk why... – Raul Chiarella Apr 06 '22 at 19:46
129

Try this:

/^stop.*$/

Explanation:

  • / charachters delimit the regular expression (i.e. they are not part of the Regex per se)
  • ^ means match at the beginning of the line
  • . followed by * means match any character (.), any number of times (*)
  • $ means to the end of the line

If you would like to enforce that stop be followed by a whitespace, you could modify the RegEx like so:

/^stop\s+.*$/
  • \s means any whitespace character
  • + following the \s means there has to be at least one whitespace character following after the stop word

Note: Also keep in mind that the RegEx above requires that the stop word be followed by a space! So it wouldn't match a line that only contains: stop

Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
58

If you want to match anything after a word, stop, and not only at the start of the line, you may use: \bstop.*\b - word followed by a line.

Word till the end of string

Or if you want to match the word in the string, use \bstop[a-zA-Z]* - only the words starting with stop.

Only the words starting with stop

Or the start of lines with stop - ^stop[a-zA-Z]* for the word only - first word only. The whole line ^stop.* - first line of the string only.

And if you want to match every string starting with stop, including newlines, use: /^stop.*/s - multiline string starting with stop.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Waxo
  • 1,816
  • 16
  • 25
  • 1
    If needing todo this with JS and some dynamic input causing you to need to use `new RegExp` it is important to know to escape the boundary (or any other flags), for example for the "stop" sample here: `new RegExp('\\b' + varStringStop + '\\w')` – Neil Gaetano Lindberg Dec 13 '21 at 15:51
24

Using the caret won't match every word beginning with "stop".

Only if it's at the beginning of a line like "stop going". @Waxo gave the right answer:

This one is slightly better, if you want to match any word beginning with "stop" and containing nothing but letters from A to Z.

\bstop[a-zA-Z]*\b

This would match all

stop (1)

stop random (2)

stopping (3)

want to stop (4)

please stop (5)

While

/^stop[a-zA-Z]*/

would only match (1) until (3), but not (4) & (5)

Sedat Kilinc
  • 2,843
  • 1
  • 22
  • 20
9

If you want to match anything that starts with "stop" including "stop going", "stop" and "stopping" use:

^stop

If you want to match the word stop followed by anything as in "stop going", "stop this", but not "stopped" and not "stopping" use:

^stop\W
Alex B
  • 24,678
  • 14
  • 64
  • 87
8
/stop([a-zA-Z])+/

Will match any stop word (stop, stopped, stopping, etc)

However, if you just want to match "stop" at the start of a string

/^stop/

will do :D

Mez
  • 24,430
  • 14
  • 71
  • 93
3

If you want the word to start with "stop", you can use the following pattern. "^stop.*"

This will match words starting with stop followed by anything.

  • 1
    Could you not just use `"^stop"`? – Stephen Rauch Dec 04 '17 at 01:58
  • It depends. While talking in terms of java syntax, we can use Pattern and Matcher object for using regex or direct use .matches() method with String object. They differ in result as below: `code` `String line = "stopped";` `String pattern = "^stop";` `Pattern r = Pattern.compile(pattern);` `Matcher m = r.matcher(line);` `System.out.println(m.find( )); //prints true` `System.out.println(line.matches(pattern)); //prints false` – Manisha Chaurasia Dec 04 '17 at 05:58
  • 1
    This matches only if the word at the beginning of the line. If words beginning with "stop" are in the middle of the line or at the end, this regex won't match. @StephenRauch if you omit [a-z]* you wouldn't get any words like "stopping" in whole. In the case of "stopping" you get "stop" and "ping" would be missing. – Sedat Kilinc Dec 10 '17 at 20:48
1
/^stop*$/i

i - in case it is case sensitive.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Charles Kasasira
  • 240
  • 1
  • 5
  • 15
0

I'd advise against a simple regular expression approach to this problem. There are too many words that are substrings of other unrelated words, and you'll probably drive yourself crazy trying to overadapt the simpler solutions already provided.

You'll want at least a naive stemming algorithm (try the Porter stemmer; there's available, free code in most languages) to process text first. Keep this processed text and the preprocessed text in two separate space-split arrays. Make sure each non-alphabetical character also gets its own index in this array. Whatever list of words you're filtering, stem them also.

The next step would be to find the array indices which match to your list of stemmed 'stop' words. Remove those from the unprocessed array, and then rejoin on spaces.

This is only slightly more complicated, but will be much more reliable an approach. If you've got any doubts on the value of a more NLP-oriented approach, you might want to do some research into clbuttic mistakes.

Robert Elwell
  • 6,598
  • 1
  • 28
  • 32
0

can you try this:

https://regex101.com/r/P3qfKG/1

reg = /stop(\w+| [^ ]+|$)/gm

it will select both stop and start with stop and next word;

3gwebtrain
  • 14,640
  • 25
  • 121
  • 247