Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript reg ex to match whole word only, bound only by whitespace

so I know \bBlah\b will match a whole Blah, however it will also match Blah in "Blah.jpg" I don't want it to. I want to match only whole words with a space on either side.

like image 514
iamnotmad Avatar asked Jun 01 '10 17:06

iamnotmad


2 Answers

You can try: \sBlah\s.

Or if you allow beginning and end anchors, (^|\s)Blah(\s|$)

This will match "Blah" by itself, or each Blah in "Blah and Blah"

See also

  • regular-expressions.info/Character classes and Anchors
    • \s stands for "whitespace character".
    • The caret ^ matches the position before the first character in the string
    • Similarly, $ matches right after the last character in the string

Lookahead variant

If you want to match both Blah in "Blah Blah", then since the one space is "shared" between the two occurrences, you must use assertions. Something like:

(^|\s)Blah(?=\s|$) 

See also

  • regular-expressions.info/Lookarounds

Capturing only Blah

The above regex would also match the leading whitespace.

If you want only Blah, ideally, lookbehind would've been nice:

(?<=^|\s)Blah(?=\s|$) 

But since Javascript doesn't support it, you can instead write:

(?:^|\s)(Blah)(?=\s|$) 

Now Blah would be captured in \1, with no leading whitespace.

See also

  • regular-expressions.info/Grouping and flavor comparison
like image 112
polygenelubricants Avatar answered Oct 05 '22 21:10

polygenelubricants


Matching all:

\bBlah\b 

Regular expression visualization

Debuggex Demo

like image 39
Peter Kreinz Avatar answered Oct 05 '22 23:10

Peter Kreinz