Regex: Match specific string unless contained in a longer string

Good morning,

I'm struggling to put together a regular expression which could be described as "match a specific string, unless it is contained within another string".

Specifically, I'm looking to match the string "nox", but not when it is in the string "monoxide".

How might I best approach this?

Will word boundaries, \b, work for you?

X <- 'match the string "nox", but not when it is in the string "monoxide".'
> gsub("\\bnox\\b", "HERE", X)
[1] "match the string \"HERE\", but not when it is in the string \"monoxide\"."
1 Like

That does the job exactly, thanks! Glad it was as easy as that!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.