0

I am working on a regex which would return true if matched words are present in any order.

This approach (discussed here: Regular Expressions: Is there an AND operator?)

(?=.*tag1)(?=.*tag2)

matches both tag1 tag2 and tag2 tag1 (http://rubular.com/r/374706hkft), in Ruby, but does not work in JavaScript. Any ideas?

Edit: by "Does not work in JS" I meant that

"tag1 tag2".match(/(?=.*tag1)(?=.*tag2)/) 

returns [""].

The answer to this question pointed out that the regex works in the format of

/(?=.*tag1)(?=.*tag2)/.test("tag1 tag2")
Community
  • 1
  • 1
aaandre
  • 2,502
  • 5
  • 33
  • 46
  • 1
    I have a hard time seeing how that would work in any regex engine – Pointy Apr 04 '15 at 00:09
  • But if `match` does return an array (instead of `null`), it *did* match! Notice that your regular expression matches the empty string (when followed by `tag1` and when followed by `tag2`), which is indeed a part of your input. – Bergi Apr 06 '15 at 17:27

1 Answers1

2

That regular expression works fine in JavaScript:

function check(s) {
    var found = /(?=.*tag1)(?=.*tag2)/.test(s);
    document.write(found + '<br>');
}

check('xxtag1xxxtag2xxxx'); // both found: true
check('xxtag2xxxtag1xxxx'); // both found: true
check('xxtag2xxxtag0xxxx'); // only one found: false
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • `/(?=.*tag1)(?=.*tag2)/.test('tag1 tag2')` works, but `"tag1 tag2".match(/(?=.*tag1)(?=.*tag2)/)` returns `[""]`. Can you tell me why one format would return a different result than the other? – aaandre Apr 06 '15 at 17:17
  • @aaandre: test returns a boolean, not the match result. They're different methods! – Bergi Apr 06 '15 at 17:25
  • @aaandre: The pattern matches a zero-length string when the string contains `tag1` and `tag2`. The `test` method returns `true` when there is a match, and there is. The `match` method returns the matches, and the zero-length string is the match. If the pattern would have anything more than the look-ahead matches, the match would be more than the zero-length string. – Guffa Apr 06 '15 at 17:29