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 :(
You can use this lookahead based regex:
^(?=.*?O)(?=.*?M)(?=.*?H)(?=.*?E)[OMHE]{4}$
Demo version of RegEx
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 ...
You can use this template
(O|M|H|E){4}
This is the way to do it if you want to make the match mobile inside
String.
# (?<!\S)([OMHE])(?!\1)([OMHE])(?!\1|\2)([OMHE])(?!\1|\2|\3)([OMHE])(?!\S)
(?<! \S )
( [OMHE] ) # (1)
(?! \1 )
( [OMHE] ) # (2)
(?! \1 | \2 )
( [OMHE] ) # (3)
(?! \1 | \2 | \3 )
( [OMHE] ) # (4)
(?! \S )