【发布时间】:2016-09-27 14:54:57
【问题描述】:
我开发了以下正则表达式以在搜索字段中使用。
目标是使用它来匹配最多 2 个单词,然后是带有字符的完整单词以及之后的所有内容:
/^
.*? # match anything before, as few times as possible
(
(?:
[^\s]+\s* # anything followed by whitespace
){1,2} # match once or twice
\s*? # match whitespaces that may be left behind, just in case
[^\s]*? # match the beginning of the word, if exists
)?
(foo|bar) # search term(s)
([^\s]*\s*.*) # whatever is after, with whitespace, if it is the end of the word
$/xi
问题在于它并不总是正确匹配。
几个例子,当搜索“a”时:
Fantastic drinks and amazing cakes
Expected match:
$1 = F
$2 = a
$3 = ntastic drinks and amazing cakes
Result:
$1 = Fantastic drinks (space)
$2 = a
$3 = nd amazing cakes
-----------------------------------------
Drinks and party!
Expected match:
$1 = Drinks (space)
$2 = a
$3 = nd party!
Result:
$1 = Drinks and p
$2 = a
$3 = rty!
------------------------------------------
Drinks will be served at the caffetary in 5 minutes
Expected match:
$1 = be served (space)
$2 = a
$3 = t the caffetary in 5 minutes
Result (matches correctly):
$1 = be served (space)
$2 = a
$3 = t the caffetary in 5 minutes
您可以在 https://regex101.com/r/cI7gZ3/1 上进行试验,包括单元测试。
这不起作用的方式很奇怪,超出了我的描述。但是,我的猜测是,这是更喜欢在搜索词之前 有 1-2 个单词的匹配项。
您认为这里可能有什么问题?您认为造成这些问题的原因是什么?
【问题讨论】:
-
Ffffantastic怎么样?应该如何捕捉零件? -
如果第二个捕获组(我称为
search term)中的内容是我的示例中使用的“a”,它应该将Ffff存储在第一个组中,并将ntastic存储在第三个。 -
我看到您接受了答案,但有一个问题:您是否只有字母和空格,或者您的输入字符串中也可以包含其他字符?
-
@revo 任何事情都很重要。它不会有换行符,但会有各种空格和符号。主要限于 ISO-8859-15/ANSI/CP-1252/Windows-1252。