Skip to content
Advertisement

Regex to match a word, even is there are spaces between letters

I’d like to have a regex to match a word, even if there are spaces between the characters. When I want to match the word test, it should match the following:

test t est t e s t

And so on, but it should not match things like this:

tste te ts s tet

I have this regex: (t[s]*e[s]*s[s]*t[s]*) But I don’t believe that this one is very efficient.

Advertisement

Answer

This is the only way to match such words. You have to consume these spaces, otherwise you won’t have a match. Actually, your pattern is the same as

ts*es*ss*t

If the word appears inside a larger string, you can consider a word boundary version:

bts*es*ss*tb

NOTE: If only one whitespace is allowed in between each letter, you can use ? quantifier instead of *:

ts?es?ss?t
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement