Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  80] [ 4]  / answers: 1 / hits: 37592  / 9 Years ago, fri, may 8, 2015, 12:00:00

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.


More From » regex

 Answers
10
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.


[#66687] Wednesday, May 6, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brianaclaras

Total Points: 23
Total Questions: 106
Total Answers: 111

Location: Japan
Member since Sat, Jun 6, 2020
4 Years ago
brianaclaras questions
Fri, Oct 15, 21, 00:00, 3 Years ago
Thu, Dec 3, 20, 00:00, 4 Years ago
Mon, May 25, 20, 00:00, 4 Years ago
Wed, Mar 4, 20, 00:00, 4 Years ago
;