Regular expression: specify "space or beginning of line" and "space or end of line"

Imagine you are trying to match a pattern with "stackoverflow".

You want the following:

this is stackoverflow and it rocks [MATCH] stackoverflow is the best [MATCH] i love stackoverflow [MATCH] typostackoverflow rules [NO MATCH] i love stackoverflowtypo [NO MATCH] 

I know how to parse stackoverflow if it has spaces on both sites using:

 /\s(stackoverflow)\s/ 

The same if its at the beginning or end of a line:

 /^(stackoverflow)\s/ /\s(stackoverflow)$/ 

But how to specify "space or end of line" and "space or beginning of line" using a regular expression?

+100
regex preg-match
Jul 15 2018-11-21T00:
source share
4 answers

You can use any of the following:

 \b #A word break and will work for both spaces and end of lines. (^|\s) #the | means or. () is a capturing group. /\b(stackoverflow)\b/ 

Also, if you do not want to include a space in your match, you can use lookbehind / forwards.

 (?<=\s|^) #to look behind the match (stackoverflow) #the string you want. () optional (?=\s|$) #to look ahead. 
+138
Jul 15 2018-11-21T00:
source share

(^|\s) will match a space or the beginning of a line and ($|\s) for a space or the end of a line. Together this:

 (^|\s)stackoverflow($|\s) 
+53
Jul 15 '11 at 21:28
source share

Here is what I will use:

  (?<!\S)stackoverflow(?!\S) 

In other words, match "stackoverflow" if it is not preceded by a character without spaces, and not a character without spaces.

This is more accurate (IMO) than the space-or-anchor approach, and it does not imply that the line begins and ends with word characters such as the \b approach.

+13
Jul 15 2018-11-18T00:
source share

\b matches word boundaries (without actually matching any characters), so the following should do what you want:

 \bstackoverflow\b 
+7
Jul 15 2018-11-21T00:
source share



All Articles