0

According to the following answer on Stack OverFlow:

(?=.*foo)(?=.*baz)

This says to the regular expression that foo must appear anywhere and baz must appear anywhere, not necessarily in that order and possibly overlapping.

This regular expression should match those words foo and baz:

Where foo have baz all my life

However this doesn't work. Nor in regexr nor in regexpal.com.

Community
  • 1
  • 1
George Chalhoub
  • 14,968
  • 3
  • 38
  • 61

3 Answers3

1

Lookarounds are only assertions which won't match any single character.

(?=.*foo)(?=.*baz) 

asserts that the line where the match going to happend must contain foo and baz strings. And i suggest you to use anchors along with the above lookarounds.

^(?=.*foo)(?=.*baz)

This would the boundary which exists at the start of a line.

Where the above regex would be helpful?

This is helpful when you want to print the whole line where the strings foo and baz appears.

In js, you could write

/^(?=.*foo)(?=.*baz)/m.test(string);
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

You need to create a capture group around foo and baz because the lookaround isn't a capture group, but an assertion.

The lookahead itself is not a capturing group. It is not included in the count towards numbering the backreferences. If you want to store the match of the regex inside a lookahead, you have to put capturing parentheses around the regex inside the lookahead, like this: (?=(regex)). The other way around will not work, because the lookahead will already have discarded the regex match by the time the capturing group is to store its match.

http://www.regular-expressions.info/lookaround.html

Make your regular expression:

(?=.+?(foo))(?=.+?(baz))

Note the capture group within the lookahead.

https://regex101.com/r/rS8sK6/1

ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49
  • That's because of the positive lookahead. It requires at least one character before (because I made the quantifier become `+?` - *my bad*). If you change the `+?` after the `.`, to quantifier `*` then it will: https://regex101.com/r/rS8sK6/2 – ʰᵈˑ Jun 11 '15 at 13:50
  • Thanks. All works now. Any idea why http://regexpal.com/ doesn't work for this expression? – George Chalhoub Jun 11 '15 at 14:02
  • No worries. Glad to help. I've never used regexpal.com, so I'm unsure. Sorry – ʰᵈˑ Jun 11 '15 at 14:05
0

If there are only two strings you are looking for, you can do:

(XXX.*YYY)|(YYY.*XXX)

It will search for XXX and YYY in the same line in both orders.

Maybe not efficient but it is simple and works.

Dr_vIQtor
  • 1
  • 1