0

The regex I want to use is: ^(?=.*[,])(,?)ABC(,?)$

What I want to get out is:

^                // start
(?=.*[,])        // contains at least one comma (,)
(,?)ABC(,?)      // The comma is either in the beginning or in the end of the string "ABC"
$                // end

Of course ABC is ought to be a variable based on my search term.

So if ABC = 'abc' then ",abc", "abc,", ",abc," will match but not "abc" or "abcd"

Better way to do this is also welcome.

The value in the record looks like "abc,def,ghi,ab,cde..." and I need to find out if it contains my element (i.e. 'abc'). I cannot change the data structure. We can assume that in no case the record will contain only one sub-value, so it is correct to assume that there always is a comma in the value.

4
  • So you wish to search for a term in a string having comma separated terms ? Commented Feb 4, 2016 at 1:54
  • Yes basically the regex tells it all. It must have one comma either in the beginning or end to make sure my string is not substring of other string, and it will match if it's first string or last as well. Commented Feb 4, 2016 at 1:58
  • how about splitting the string with comma delimiter then search after splitting? Commented Feb 4, 2016 at 2:01
  • What you currently have is correct. Just don't use ^ and $. Use only (,?)(ABC)(,?) and capture the second group by using $2 or \2 whatever is compatible with sql-server. Or by using non capturing groups like this. Commented Feb 4, 2016 at 2:04

1 Answer 1

2

If you want to know if a comma delimited string contains abc, then I think like is the easiest method in any database:

where ',' + col + ',' like '%,abc,%'
Sign up to request clarification or add additional context in comments.

3 Comments

That will not match "abc,def"
"abc" could be the first or last item
@Ddan . . . Of course this will. That is why commas are pre- and post-pended before the like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.