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

喜夏-厌秋 提交于 2019-12-20 07:47:56

问题


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.


回答1:


Actually, it is the same as t\s*e\s*s\s*t (if the word appears inside a larger string, \bt\s*e\s*s\s*t\b is preferable). This is the only way to match such words. You have to consume these spaces, otherwise you won't have a match.




回答2:


Why not remove all horizontal spaces from input and then match regex:

$input = 't e s t';
$regex = '/\btest\b/i';

preg_match($regex, preg_replace('/\h+/', '', $input), $m);


来源:https://stackoverflow.com/questions/29363421/regex-to-match-a-word-even-is-there-are-spaces-between-letters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!