0

我想捕获任何与 %[a-z0-9] 匹配的字符串,遵循以下示例:

1. %xxxxxxxxxxxxx                                 //match
2. this will work %xxxxxx but not this%xxxxxxxxx. //match 1st, not 2nd
3. and also %xxxxxxxxxx.                          //match
4. just a line ending with %xxxxxxxxxxx           //match
5. %Xxxxxxxxxxx                                   //no match
6. 100% of dogs                                   //no match
7. 65%. Begining of new phrase                    //no match
8. 65%.Begining of new phrase                     //no match

它可以在字符串的开头或结尾,但不能在单词的中间。它当然可以在字符串中作为单词(以空格分隔)。

我努力了

/(\b)%[a-z0-9]+(\b)/
/(^|\b)%[a-z0-9]+($|\b)/
/(\w)%[a-z0-9]+(\w)/

和其他人喜欢这样,但我不能让它像我一样工作。我猜 \b 标记在示例 2 中不起作用,因为 % 符号之前有一个边界。

任何帮助将不胜感激。

4

2 回答 2

1

尝试

/\B%[a-z0-9]+\b/

空格和 之间没有单词边界 ,但和之间有一个。\b%s%

\B\b非单词边界相反。

regex101上查看

于 2015-03-12T11:17:44.910 回答
0
%[a-z0-9]+(?=\s|$)|(?:^|(?<=\s))%[a-z0-9]+

试试这个。看演示。

https://regex101.com/r/iS6jF6/20

$re = "/%[a-z0-9]+(?=\\s|$)|(?:^|(?<=\\s))%[a-z0-9]+/m";
$str = "1. %xxxxxxxxxxxxx //match\n2. this will work %xxxxxx but not this%xxxxxxxxx. //match 1st, not 2nd\n3. and also %xxxxxxxxxx. //match\n4. just a line ending with %xxxxxxxxxxx //match\n5. %Xxxxxxxxxxx //no match\n6. 100% of dogs //no match\n7. 65%. Begining of new phrase //no match\n8. 65%.Begining of new phrase //no match";

preg_match_all($re, $str, $matches);

或者

%[a-z0-9]+\b|\b%[a-z0-9]+
于 2015-03-12T11:21:25.980 回答