kentcdodds
kentcdodds

Reputation: 29031

Why is this regex not matching like the other?

I am trying to match the inner-most content between @@BOKeyword- and -End@@ in the following example:

@@BOKeyword-Here is@@BOKeyword-I want to match this!-End@@stuff-End@@

So my match would be: I want to match this! I'm using the following regex: @@BOKeyword-([^@@BOKeyword--End@@]*)-End@@

However, this doesn't match at all. I developed this based on this example which I derived from a previous question's answer:

AC I want to match this! BD I don't want to match this! AC I want to match this! BD I don't want to match this! BD

Using the regex: AC([^ACBD]*)BD

And this works as expected. I think I'm misunderstanding how this works. Any tips would be appreciated! Thanks!

Note: I'm running this in Java.

Upvotes: 0

Views: 46

Answers (1)

kev
kev

Reputation: 161674

If your regex engine support lookaround, you can try this:

(?<=@@BOKeyword-).((?<!@@BOKeyword-).(?!-End@@))*.(?=-End@@)
  • the first DOT matches start character: I
  • the middle DOT matches characters not surrounded by your delimiters: ·want·to·match·this
  • the last DOT matches end character: !

There are 2 cases not cover (only one/zero character in between):

(?<=@@BOKeyword-).?(?=-End@@)

It's pretty hard to combine these two regex. Another way is:

  • replace your delimiters with {/} (or other single character pair)
  • write a simpler regex to match

Upvotes: 1

Related Questions