Regex to make sure that outside a certain tag there aren't any other tags

Viewed 25

I'm trying to create a regular expression that makes sure that there are no other tags outside a certain tag.

The following should fail:

  • This <F>is</F> a test <ID><F>sentence</F></ID> for stackoverflow.
  • This <ID><M>is</M></ID> a test <F>sentence</F> for stackoverflow.

This one should pass:

  • This is a test <ID><F>sentence</F></ID> for stackoverflow.
  • This is a test <ID><F>sentence</F></ID> for <ID>stackoverflow.</ID>

This is what I have tried so far:

  1. Match the correct tag: (<ID>.+?<\/ID>)
  2. Make sure that there are no tags before the matched tag: (?<![<>].+?)(<ID>.+?<\/ID>)
  3. Make sure that there are no tags after the matched tag: (?<![<>].+?)(<ID>.+?<\/ID>)(?!.+?[<>])

Part 3 is where the problem relies. When I add this part the match just expands to the last tag in order to satisfy the negative lookahead as you can see in the following screenshots:

  • No negative lookahead: No negative lookahead

  • Negative lookahead: Negative lookahead

0 Answers
Related