Multiple words in any order using regex

Viewed 151307

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

For example, I need to extract the words test and long from the following sentence whether the word test comes first or long comes.

This is a very long sentence used as a test

UPDATE: What I did not mention in the first part is that it needs to be case insensitive as well.

8 Answers

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.

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)/

without knowing what language

 /test.*long/ 

or

/long.*test/

or

/test/ && /long/

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.

Vim has a branch operator \& that allows an even terser regex when searching for a line containing any number of words, in any order.

For example,

/.*test\&.*long

will match a line containing test and long, in any order.

See this answer for more information on usage. I am not aware of any other regex flavor that implements branching; the operator is not even documented on the Regular Expression wikipedia entry.

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.

Related