I have a list of words, for example, "at", "in", "on". I need to match any of those exact words but I'm having some difficulty with one part of it.
Examples:
"I am at work" - should match with "at"
"I am attracting honey bees" - should not match
"I am at123" - should match
I currently have something like this, but it's not doing exactly what i need.
(?i)(\W|^)(at|in|on)(\W|$)
Any assistance is appreciated
CodePudding user response:
It appears that you want to match these words when surrounded by either whitespace, numbers, or the start/end of the string. In that case, we can try using the following pattern:
(?:(?<!\S)|(?<!\D))(?:at|in|on)(?:(?!\S)|(?!\D))
This pattern says to:
(?:
(?<!\S)
lookbehind and assert whitespace or the start of the string precedes|
OR(?<!\D)
lookbehind and assert that a digit or the start of the string precedes
)
(?:at|in|on)
matchat
,in
, oron
(?:
(?!\S)
lookahead and assert whitespace or the start of the string follows|
OR(?!\D)
lookahead and assert that a digit or the start of the string precedes
)