Reputation: 155
I'm looking to write a regex that will only give me the words that contains the letters that I specify and the length of the matched word should be the same as the number of characters specified.
So if I give the letters OMHE
it should only match words that contain these and only these letters as well as only the amount of times the letter comes forth in the letter sequence
The regex I have so far this specific example is(I dynamically build the regex otherwise)...
.*?[O{1}M{1}H{1}E{1}]{4}
It does work to some degree, but I do get some words that should not match.
Words that should match for the example are HOME
, but MEMO
and HOMEE
should not. I'm really bad when it comes to regexes :(
Upvotes: 3
Views: 243
Reputation: 298579
You may use ^(([OMHE])(?!.*\2)){4}$
It uses negative look-ahead saying, that after each match of [OMHE]
is captured, no other occurrence of the captured text is allowed. Then, four repetitions of it are required. Since the outer group is only there for defining the repetition, it may be optimized to be a non-capturing group:
^(?:([OMHE])(?!.*\1)){4}$
It’s easy to expand this to more characters…
Upvotes: 1
Reputation: 786146
You can use this lookahead based regex:
^(?=.*?O)(?=.*?M)(?=.*?H)(?=.*?E)[OMHE]{4}$
Upvotes: 4