Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match any/all of multiple words in a string

I'm trying to write this regEx (javascript) to match word1 and word2 (when it exists):

This is a test. Here is word1 and here is word2, which may or may not exist.

I tried these:


(word1).*(word2)?

This will match only word1 regardless if word2 exists or not.


(word1).*(word2)

This will match both but only if both exists.


I need a regex to match word1 and word2 - which may or may not exist.

like image 597
Azevedo Avatar asked May 08 '15 01:05

Azevedo


People also ask

How do you regex multiple words?

However, to recognize multiple words in any order using regex, I'd suggest the use of quantifier in regex: (\b(james|jack)\b. *){2,} . Unlike lookaround or mode modifier, this works in most regex flavours.

What does ?= Mean in regex?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

What is b regex?

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a “word boundary”. This match is zero-length. There are three different positions that qualify as word boundaries: Before the first character in the string, if the first character is a word character.


1 Answers

var str = "This is a test. Here is word1 and here is word2, which may or may not exist.";
var matches = str.match( /word1|word2/g );
//-> ["word1", "word2"]

String.prototype.match will run a regex against the string and find all matching hits. In this case we use alternation to allow the regex to match either word1 or word2.

You need to apply the global flag to the regex so that match() will find all results.

If you care about matching only on word boundaries, use /\b(?:word1|word2)\b/g.

like image 138
Phrogz Avatar answered Sep 28 '22 09:09

Phrogz