I am trying to match words with up to two missing letters with regex. For example, if the word of interest is 'hello', I want to match the following strings:
hello
hell
helo
hllo
ello
hel
heo
elo
llo
I can use the regex h?e?l?l?o? to match these, but this will also match 0, 1, and 2 letter strings as well. How can I require the match to be 3-5 characters long?
You can use a look ahead to check for 3-5 of those characters:
(?=[hello]{3,5})h?e?l?l?o?
Note that this will find a match like in a string like help since help contains hel. If you want to stp that you can check word boundaries or ends of string depending on your situation. If you want to match the ends of the sting add a ^ to the beginning and a $ to the end. If you want to check word boundaries add \b to both ends.
I think this will work ((?=.{3,})h?e?l?l?o?) - your regex, with "at least 3 characters" added on.
You probably want this to only match whole words as well (not the start of something like "hellow"), so add \b to the start and the end: \b((?=.{3,})h?e?l?l?o?)\b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With