简体   繁体   中英

Regex for finding exact words

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 :(

You can use this lookahead based regex:

^(?=.*?O)(?=.*?M)(?=.*?H)(?=.*?E)[OMHE]{4}$

RegEx Demo

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…

您可以使用此模式

(O|M|H|E){4}

This is a way to do it if you want to make the match mobile within
the 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM