Rick
Rick

Reputation: 565

how to match multiple words in string using regex?

I am trying to match 3 words that can appear anywhere in the string:

Win
Enter
Now

All 3 words must exist in the string for it return as a match. But I am having issues for getting a match when all 3 words do exist.

Below is the regex I am using: http://regexr.com/39b83

^(?=.*?win)(?=.*?(enter))(?=.*?(now)).*

Regex is working when all three words are within the same line... when its spread out across the entire string on different lines, it is failing to match.

Any direction or help is appreciated.

Upvotes: 1

Views: 3631

Answers (5)

Avinash Raj
Avinash Raj

Reputation: 174706

I think C# would support (?s) DOTALL modifier. If yes then you could try the below regex,

(?i)(?s)win.*?enter.*?now

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

It 's because the dot doesn't match the newline character. To change this, you have to ways. The first, use the s modifier (that allows the dot to match newlines):

(?s)^(?=.*\bwin\b)(?=.*\benter\b)(?=.*\bnow\b).*

But this feature isn't always available (for example in Javascript). The second way consists to replace the dot with [\s\S] (a character class that matches all the characters):

^(?=[\s\S]*\bwin\b)(?=[\s\S]*\benter\b)(?=[\s\S]*\bnow\b)[\s\S]+

Upvotes: 0

Ry-
Ry-

Reputation: 224913

It sounds like you want to match the lines on which these words appear, across up to three lines. That’s not really easy, but:

/^.*win.*(?:\s+.*)?enter.*(?:\s+.*)?now.*|^.*win.*(?:\s+.*)?now.*(?:\s+.*)?enter.*|^.*enter.*(?:\s+.*)?win.*(?:\s+.*)?now.*|^.*enter.*(?:\s+.*)?now.*(?:\s+.*)?win.*|^.*now.*(?:\s+.*)?win.*(?:\s+.*)?enter.*|^.*now.*(?:\s+.*)?enter.*(?:\s+.*)?win.*/igm

should do it.

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53525

Since you don't want to match words like center (with the word "enter"), I would use:

/(\benter\b)|(\bwin\b)|(\bnow\b)/

Link to Fiddler

Upvotes: 2

Billy Moon
Billy Moon

Reputation: 58531

How about...

/(win|enter|now)/gi

regex diagram

Upvotes: 1

Related Questions