user3243499
user3243499

Reputation: 3161

What is the proper way to check if a string contains a set of words in regex?

I have a string, let's say, jkdfkskjak some random string containing a desired word

I want to check if the given string has a word from a set of words, say {word1, word2, word3} in latex.

I can easily do it in Java, but I want to achieve it using regex. I am very new to regular expressions.

Upvotes: 1

Views: 1182

Answers (2)

Luis Colorado
Luis Colorado

Reputation: 12688

if you want only to recognise the words as part of a word, then use:

(word1|word2|...|wordn)

(see first demo)

if you want them to appear as isolated words, then

\b(word1|word2|...|wordn)\b

should be the answer (see second demo)

Upvotes: 2

Yashdeep Hinge
Yashdeep Hinge

Reputation: 405

I am not able to understand the complete context like what kind of text you have or what kind of words will this be but I can offer you a easy solution the literal way programmatically you can generate this regex (dormammu|bargain) and then search this in text like this "dormammu I come to bargain". I have no clue about latex but I think that is not your question.

For more information you can tinker with it at [regex101][1].

If you are having trouble understanding it [regexone][2] this is the place to go. For beginners its a good start.

[1]: http://regex101.com [2]: https://regexone.com/

Upvotes: 0

Related Questions