Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex To find words with missing letters

Tags:

regex

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?

like image 894
PeterM Avatar asked Jul 28 '11 04:07

PeterM


2 Answers

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.

like image 143
Paul Avatar answered Oct 31 '22 05:10

Paul


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

like image 38
porges Avatar answered Oct 31 '22 03:10

porges