Reputation: 1188
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
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,])
Upvotes: 4