正则表达式匹配一个单词,即使字母之间也有空格

时间:2022-11-28 22:05:54

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时,它应匹配以下内容:

test t est t e s t

测试结果

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

等等,但不应该匹配这样的事情:

tste te ts s tet

t t te t 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.

我有这个正则表达式:(t [\ s] * e [\ s] * s [\ s] * t [\ s] *)但我不相信这个非常有效。

2 个解决方案

#1


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.

实际上,它与t \ s * e \ s * s \ s * t相同(如果单词出现在较大的字符串中,则优选\ bt \ s * e \ s * s \ s * t \ b)。这是匹配这些单词的唯一方法。您必须消耗这些空格,否则您将无法匹配。

#2


1  

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);

#1


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.

实际上,它与t \ s * e \ s * s \ s * t相同(如果单词出现在较大的字符串中,则优选\ bt \ s * e \ s * s \ s * t \ b)。这是匹配这些单词的唯一方法。您必须消耗这些空格,否则您将无法匹配。

#2


1  

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);