正则表达式:
/([^]+):([^\\r\\n]+)/
字符串:
f1:aaa\r\nf2:bbb\r\nf3:ccc\r\nf4:ddd
根据 regexpal.com,这将给出我想要的集合:f1 & aaa、f2 & bbb、f3 & ccc
等。
但是使用 http://www.functions-online.com/preg_match.html我只看到 [0] => "f1"和 [1] => "f1"
谁能告诉我应该怎么做?
最佳答案
一些 javascript 实现允许 []
和 [^]
分别为“无字符”和“任何字符”。但请记住,这是 javascript 正则表达式特有的。 (如果您对该主题感兴趣,可以查看 this post。)
换句话说 [^]
是 [\s\S]
的快捷方式因为 javascript 没有点可以匹配换行符的 dotall 或 singleline 模式。
因此,要在 PHP 中获得相同的结果,您必须替换 [^]
通过 .
(默认情况下匹配除换行符以外的任何字符)与单行修饰符 s
在结束定界符或 (?s)
之后在 .
之前也允许换行。示例:/.+/s
或 /(?s).+/
但对于您的特定情况,这种模式似乎更合适:
preg_match_all('~((?>[^rn\\\:]++|(?<!\\\)[rn])+):([^\\\]++)~', $subject, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
echo $match[1].' '.$match[2].'<br/>';
}
图案解释:
~ # pattern delimiter
( # open the first capturing group
(?> # open an atomic group
[^rn\\\:]++ # all characters that are not "r", "n", "\" or ":"
| # OR
(?<!\\\)[rn] # "r" or "n" not preceded by "\"
)+ # close the atomic group and repeat one or more times
) # close the first capturing group
:
( # open the second capturing group
[^\\\]++ # all characters except "\" one or more times
) # close the second capturing group
~
声明:
当你想表示一个 \
时(反斜杠)在单引号包围的字符串中,必须使用双转义:\\\
该模式的原理是使用否定字符类和否定断言,换句话说,它寻找所需的子字符串不能是什么。
以上模式使用原子组 (?>...)
和所有格量词 ++
代替非捕获组(?:...)
和简单量词 +
.它是相同的,除了正则表达式引擎在原子组和所有格量词失败时不能返回测试其他方式,因为它不记录回溯位置。您可以通过这种功能赢得性能。
关于php - 正则表达式适用于 Javascript 但不适用于 PHP preg_match,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18510976/