Stan Zeez
Stan Zeez

Reputation: 1188

Check that a comma-separated string of codes contains the given code using regex

I try to resolve my task using regex.

Given:

string of comma-seprated codes:

" 1004, 1001 , 11004, 1002, 1003, 1004 ,  1005,ABC100,10041,ABC102, 1004 "

code to check. For example:

"1004"

Goal:

Need to sure that the given code contains in the source string.

I prepared an ugly pattern but it works:

(?:,|^)[ ]*1004[ ]*(?=,)|(?<=,)[ ]*1004[ ]*(?:,|$)|^[ ]*1004[ ]*$

https://regex101.com/r/4IEi42/1

Is it possible to simplify it using the code one time in the pattern? Thanks!

Upvotes: 1

Views: 41

Answers (1)

bobble bubble
bobble bubble

Reputation: 18545

A simpler idea can be to check by use of negated classes and negative lookarounds if the searchterm is neither preceded nor followed by characters that are not , or white-space.

(?<![^\s,])1004(?![^\s,])

See demo at regex101

Upvotes: 4

Related Questions