Matching in a comma-separated list with Regular Expressions

Tonight’s quiz:
How to see if ‘foo’ is a unique entry in comma-separated list ‘foo,bar,foobar,foo,foo’?

We want to match the ‘foo’ at the beginning, at the end, and also in the middle, but not as part of the word ‘foobar.’ Also the comma-separated list might only be ‘foo’.

First attempt:
[^,]foo[$,]

Plain wrong, because ^ means something different inside a set

Second attempt:
^foo$|^foo,|,foo,|,foo$

Works, but clunky.

Third attempt:
bfoob

Works perfectly. Especially when you remember to escape the ” in your .NET string assignment 🙁

Thanks to the Rad Software Regular Expression Designer too!

Leave a Reply

Your email address will not be published. Required fields are marked *