Shades88
Shades88

Reputation: 8360

How to create a regex to check whether a set of words exists in a given string?

How can I write a regex to check if a set of words exist in a given string?

For example, I would like to check if a domain name contains "yahoo.com" at the end of it.

'answers.yahoo.com', would be valid.
'yahoo.com.answers', would be wrong. 'yahoo.com' must come in the end.

I got a hint from somewhere that it might be something like this.

"/^[^yahoo.com]$/"

But I am totally new to regex. So please help with this one, then I can learn further.

Upvotes: 0

Views: 3861

Answers (1)

Brock Adams
Brock Adams

Reputation: 93523

When asking regex questions, always specify the language or application, too!

From your history it looks like JavaScript / jQuery is most likely.

Anyway, to test that a string ends in "yahoo.com" use /.*yahoo\.com$/i

In JS code:

if (/.*yahoo\.com$/i.test (YOUR_STR) ) {
    //-- It's good.
}


To test whether a set of words has at least one match, use:

/word_one|word_two|word_three/


To limit matches to just the most-common, legal sub-domains, ending with "yahoo.com", use:

/^(\w+\.)+yahoo\.com$/

(As a crude, first pass)

For other permutations, please clarify the question.

Upvotes: 1

Related Questions