1

I've this Regex:

(\[\[.*?\]\])(?<!".*?)

Regular expression visualization

Debuggex Demo

and this test data:

[[Hello]]
<tag Text="my [[Test]] is [[Test2]] for [[Test3]][[Test4]]">

How can I get that look-behind to ignore those that are preceded by a "?

It should match the [[Hello]] but not the remainder. However, it is of course matching them all.

Mike Perrenoud
  • 63,395
  • 23
  • 143
  • 222

2 Answers2

4

Your regular expression actually does the job for your specific input, I would write.. ( Working Demo )

\[\[[^]]*\]\](?<!"[^"]*)

You may also consider using the alternation operator in context placing what you want to exclude on the left, ( saying throw this away, it's garbage ) and place what you want to match in a capturing group on the right side.

And then you can refer to the capturing group to get your match result. ( Working Demo )

"[^"]*"|(\[\[[^]]*\]\])
hwnd
  • 65,661
  • 4
  • 77
  • 114
  • @AmalMurali It is a great used method for purposes like this where you can avoid lookarounds. – hwnd Aug 07 '14 at 19:05
  • Indeed. I first came to know about it via [this answer](http://stackoverflow.com/a/23589204/1438393) by [zx81](http://stackoverflow.com/users/1078583/zx81) :) – Amal Murali Aug 07 '14 at 19:07
1

Discard technique

You can use the regex technique to discard what you dont want. It consists of having a pattern line:

discard1|other discard|more crap|(the content I want)

Regular expression visualization

Notice that the content you want is the one on the rightest side and within capturing groups:

Said that, you can use this regex:

.*".*".*|.*?(\[\[.*?\]\]).*?

Working demo

MATCH 1
1.  [0-9]   `[[Hello]]`

Lookaround

On the other hand, if you want to use regex lookaround (lookbehind and lookahead) you can use this regex:

(?<!").*?(\[\[.*?\]\])(?!.*")

Working demo

Regular expression visualization

But I like the discard technique, it's very clear and can save many headaches. You can learn many about it if you look for zx81, anubhava posts, they rock on regex.

Federico Piazza
  • 27,409
  • 11
  • 74
  • 107