简体   繁体   中英

Generate regex for exact words from a list

I am trying to write a regex that can match any word in the following or similar words. * in these strings are exact * and not any character.

Jump
J**p
J*m*
J***
***p
J***ing
J***ed
****ed

I want to keeo the length fixed.

1. Any string of lenght 4 that matches the string 'jump' 
2. Any string of length 6 that matches 'jumped' 
3. Any string of length 7 that matches 'jumping' 

I was using the following statements but for some reason, i am not able to to the correct translation. It accepts other strings as well.

p = re.compile('j|\*)(u|\*)(m|\*)...)
bool(p.match('******g'))

This is a fairly straightforward regex. We want to match a word, but allow each character to be an asterisk. The regex is therefore a sequence of character groups of the form [x*] :

[Jj*][u*][m*][p*](?:[i*][n*][g*]|[e*][d*])?

See it in action at regex101.

If you only want to match these exact words, make sure to use the pattern with re.fullmatch .

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