crazy_dd
crazy_dd

Reputation: 135

Find words in strings which contain specific characters only

I am trying to write regex to find words which contain specific characters only.

For ex :

text= "I want to mes a message saying mess"

I want regex to find words which contain characters only "m" "e" "s" i.e mes and mess.

I don't want regex to find message as it contains other characters than "m" "e" "s".

reg= r"(?:[mes"]){1,} is what am trying....

Also can you please help me in writing a regex which contains words starting with me but does not contain words like men meal

text=" Regex should find mess mean and all words starting with me except men and meal"

Output should be only : mess mean me

Thanks...

Upvotes: 0

Views: 752

Answers (3)

The Scientific Method
The Scientific Method

Reputation: 2436

Also can you please help me in writing a regex which contains words starting with me but does not contain words like men meal

Yes. try the following:

(?!(\bmeal\b)|(\bmen\b))\bme\w+

see this link for explanation and demo

Upvotes: 0

KC.
KC.

Reputation: 3107

This my way,without regex

text = "I want to mes a message saying mess".split()
rtext = [t for t in text if t.find("me") == 0] # only find word begin with `me`
xtext = [t for t in text if "me" in t] #May be too broad
print(rtext)

Upvotes: 1

Loois95
Loois95

Reputation: 85

I think it is \b[mes]+\b but I think there are more ways to do this

Upvotes: 2

Related Questions