While doing some small regex task I came upon this problem. I have a string that is a list of tags that looks e.g like this:
foo,bar,qux,garp,wobble,thud
Just use look-arounds to solve this:
(?<=^|,)garp(?=$|,)
The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.
You can't use ^
and $
in character classes in the way you wish - they will be interpreted literally, but you can use an alternation to achieve the same effect:
(^|,)garp(,|$)
you just need to use word boundary (\b
) instead of ^
and $
:
\bgarp\b