-2

From answer of @skyfoot at this question regex-lookahead-lookbehind-and-atomic-groups

He said that:

given the string `foobarbarfoo`

    bar(?=bar)     finds the first bar.
    bar(?!bar)     finds the second bar.
    (?<=foo)bar    finds the first bar.
    (?<!foo)bar    finds the second bar.

you can also combine them

    (?<=foo)bar(?=bar)    finds the first bar.


What's happened suppose i have string "barfoobarbarfoo"

And i want to find these bold text

"barfoobarbarfoo"

The regex might be: (?<=bar)foo(????)bar(?=foo)

The question is that what expression should be in the middle (look ahead or look behide)?

Community
  • 1
  • 1
fronthem
  • 4,011
  • 8
  • 34
  • 55

2 Answers2

1

try this pattern

foo(?=bar)|(?<=bar)bar  

Demo

alpha bravo
  • 7,838
  • 1
  • 19
  • 23
1

To complete your example:

bar(?=bar)     finds the `bar` followed by `bar`
bar(?!bar)     finds the `bar` NOT followed by `bar`
(?<=foo)bar    finds the `bar` preceeded by `foo`
(?<!foo)bar    finds the `bar` NOT preceeded by `foo`

So, in your case, you want the foo preceeded by bar AND followed by bar. Using the example above, this should give:

(?<=bar)foo(?=bar)

Then, to find the bar preceeded by bar AND followed by foo you should use:

(?<=bar)bar(?=foo)

Finally, to combine those two patterns, you should use the OR operator and you end up with the following:

(?<=bar)foo(?=bar)|(?<=bar)bar(?=foo)

DEMO

Enissay
  • 4,969
  • 3
  • 29
  • 56
  • I started anwsering before you accept the other answer xD ... I'll leave it though if more exaplanations are needed ;-) – Enissay Dec 26 '14 at 22:57