Regex: Use start of line/end of line signs (^ or $) in different context

Posted by fgysin on Stack Overflow See other posts from Stack Overflow or by fgysin
Published on 2010-03-31T11:25:39Z Indexed on 2010/03/31 11:33 UTC
Read the original article Hit count: 479

Filed under:
|

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

What I needed to do was to check if a certain tag, e.g. 'garp' was in this list. (What it finally matches is not really important, just if there is a match or not.)

My first and a bit stupid try at this was to use the following regex:
[^,]garp[,$]

My idea was that before 'garp' there should either be the start of the line/string or a comma, after 'garp' there should be either a comma or the end of the line/string.

Now, it is instantly obvious that this regex is wrong: Both ^ and $ change their behaviour in the context of the character class [ ].

What I finally came up with is the following:
^garp$|^garp,|,garp,|,garp$

This regex just handles the 4 cases one by one. (Tag at beginning of list, in the center, at the end, or as the only element of the list.) The last regex is somehow a bit ugly in my eyes and just for funs sake I'd like to make it a bit more elegant.

Is there a way how the start of line/end of line characters (^ and $) can be used in the context of character classes?

© Stack Overflow or respective owner

Related posts about regex

Related posts about beginner