12

I don't understand that much regular expression and I want to create one that matches two strings.

I know that for one string the code is .match(/something/) and if matches on of two strings it is .match(/something|someotherthing/)

How to write one that only matches when both strings are found in the text e.g "google microsoft"

Idrizi.A
  • 9,819
  • 11
  • 47
  • 88

3 Answers3

21

To do it with a single regular expression, you'll need to account for the fact that they could come in either order. (.* matches any characters in between the two substrings):

/google.*microsoft|microsoft.*google/

Note: If you wanted to do more than 2 substrings this would get out of hand. 3 strings could come in 6 different orders, 5 strings could come in 120 orders, and 10 substrings could be ordered 3628800 different ways! That's why using features of the language (Javascript) itself, like in Explosion Pills answer, can be much better than trying to do too much with a regular expression.

Paul
  • 139,544
  • 27
  • 275
  • 264
11

The other answers are perfectly fine for your specific problem, but as Paulpro noted really get out of hand when you have more than two words.

The easiest way out is to use multiple checks as Explosion Pills suggests.

But for a more scalable regex-only approach you can use lookaheads:

/^(?=.*google)(?=.*microsoft)(?=.*apple).../

The lookahead doesn't actually consume anything, so after the first condition is checked (that .*google can match), you are back at the beginning of the string and can check the next condition. The pattern only passes if all lookaheads do.

Note that if your input may contain line breaks, .* will not do. You'll have to use [^]* or [\s\S]* instead (same goes for the others' answers).

Martin Ender
  • 43,427
  • 11
  • 90
  • 130
8

You could just use .match twice

str.match(/google/) && str.match(/microsoft/)

In that case it may be faster to use .indexOf

You can also use a verbose regex

.match(/google.*microsoft|microsoft.*google/)
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • I know that I can use `match` twice but I wanted it with regex in order to make it shorter.. but with regex it seems to be longer than using `match` twice – Idrizi.A Aug 28 '13 at 19:43
  • @Enve short code isn't necessarily the most readable one. Especially if the "long" code already fits in one or two lines. – Martin Ender Aug 28 '13 at 19:44
  • using complex regex is not about length, readability, fanciness, but the real value is it's performance. It does not have to iterate through the input twice, so if you have a huge input, it can be significantly faster. – Ivan Marinov May 24 '17 at 10:11