How to match word surronded by spaces OR at the end / beginning of the string using Perl regexp?

You can do the or inside the regex:

/(^|\s+)qwe45rty(?=\s+|$)/

regex101

Note that the second group is a positive lookahead (?=) so it checks for whitespace, but doesn't consume it. That way the regex can match two consecutive occurrences of the string and give an accurate match count.


Try coming at the problem from a different direction. To say something can match whitespace or nothing is to say it can't match a non-whitespace character:

(?<!\S)qwe45rty(?!\S)

Just a little shift in perspective and the regex practically writes itself.

Tags:

Regex

Perl