Regular expression to find exact words
I want to write a regex that will only give me words containing the letters that I specify, and the length of the matched word must be the same as the number of characters specified.
Therefore, if I give letters OMHE
, it should only match words that contain these and only those letters, and also only the number of times the letter appears in a sequence of letters
In regex, I am a concrete example so far (I create regex dynamically otherwise) ...
.*?[O{1}M{1}H{1}E{1}]{4}
This works to some extent, but I get multiple words that shouldn't be the same. Words that should correspond to the example, HOME
but MEMO
and HOMEE
have not. I feel really bad when it comes to regexes :(
source to share
you can use ^(([OMHE])(?!.*\2)){4}$
It uses negative prediction, saying that after each match [OMHE]
, no other occurrence of the captured text is allowed. Then four reps are required. Since the outer group only exists to define repetition, it can be optimized as a non-capturing group:
^(?:([OMHE])(?!.*\1)){4}$
It's easy to expand to more symbols ...
source to share