Jon M
Jon M

Reputation: 674

RegEx negative-lookahead and behind to find characters not embedded within a wrapper

I would like to match strings/characters that are not surrounded by a well-defined string-wrapper. In this case the wrapper is '@L@' on the left of the string and '@R@' on the right of the string.

With the following string for example:

This is a @L@string@R@ and it's @L@good or ok@R@ to change characters in the next string

I would like to be able to search for (any number of characters) to change them on a case by case basis. For example:

  1. Searching for "in", would match twice - the word 'in', and the 'in' contained within the last word 'string'.
  2. Searching for a "g", should be found within the word 'change' and in the final word string (but not the first occurrence of string contained within the wrapper).

I'm somewhat familiar with how lookahead works in the sense that it identifies a match, and doesn't return the matching criteria as part of the identified match. Unfortunately, I can't get my head around how to do it.

I've also been playing with this at http://regexpal.com/ but can't seem to find anything that works. Examples I've found for iOS are problematic, so perhaps the javascript tester is a tiny bit different.

I took some guidance from a previous question I asked, which seemed to be almost the same but sufficiently different to mean I couldn't work out how to reuse it:

Replacing 'non-tagged' content in a web page

Any ideas?

Upvotes: 0

Views: 514

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174834

At first all the @L@ to @R@ blocks and then use alternation operator | to match the string in from the remaining string. To differentiate the matches, put in inside a capturing group.

@L@.*?@R@|(in)

DEMO

OR

Use a negative lookahead assertion. This would match the sub-string in only if it's not followed by @L@ or @R@, zero or more times and further followed by @R@. So this would match all the in's which was not present inside the @L@ and @R@ blocks.

in(?!(?:(?!@[RL]@).)*@R@)

DEMO

Upvotes: 1

Related Questions