tags:

views:

166

answers:

5

As the title says , i need to find 2 specific words in a sentence. But they can be in any order and any casing. How do i go about doing this using regex.

E.g. This is a very long sentence used as a test

From that sentence i need to extract the words test and long in any order i.e. test can be first or long can be first.

UPDATE: What i did not mention the first part is it needs to be case insensitive as well

+1  A: 

without knowing what language

 /test.*long/

or

/long.*test/

or

/test/ && /long/
ghostdog74
I'd add word boundaries, e.g. `/\btest\b/`.
Helen
A: 

I don't think that you can do it with a single regex. You'll need to d a logical AND of two - one searching for each word.

phatmanace
+1  A: 

Use a capturing group if you want to extract the matches: (test)|(long) Then depending on the language in use you can refer to the matched group using $1 and $2, for example.

Paul Lydon
I used this answer in conjunction with the (?i) from the answer below, This resulted in the following out put (?i)(test(long)?) because it turns out i had to test for test first and then long. If it is the correct way is another story but it worked for me
RC1140
A: 

Try this:

/(?i)(?:test.*long|long.*test)/

That will match either test and then long, or long and then test. It will ignore case differences.

Daniel
+1  A: 

I assume (always dangerous) that you want to find whole words, so "test" would match but "testy" would not. Thus the pattern must search for word boundaries, so I use the "\b" word boundary pattern.

/(?i)(\btest\b.*\blong\b|\blong\b.*\btest\b)/
Paul Chernoch