0

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.

Community
  • 1
  • 1
kentcdodds
  • 27,113
  • 32
  • 108
  • 187
  • `[]` groups match (positively or negatively) one character at a time. Not entire strings. So `[^ABCD]` actually means a single character that is not A,B,C or D. – Mike Park Nov 06 '12 at 23:55

1 Answers1

1

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
kev
  • 155,172
  • 47
  • 273
  • 272