正则表达式:
/([^]+):([^\\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" and [1] => "f1"
谁能展示我应该怎么做?
正则表达式:
/([^]+):([^\\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" and [1] => "f1"
谁能展示我应该怎么做?
javascript的一些实现分别允许[]
和[^]
作为“无字符”和“任何字符”。但请记住,这是 javascript 正则表达式特有的。(如果你对这个主题感兴趣,你可以看看这篇文章。)
换句话说[^]
,这是一个快捷方式,[\s\S]
因为 javascript 没有点可以匹配换行符的dotall或单行模式。
因此,要在 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
~
注意事项:
当您想\
在用单引号括起来的字符串中表示(反斜杠)时,您必须使用双转义:\\\
这种模式的原理是使用否定字符类和否定断言,换句话说,它查找所需的子字符串不能是什么。
上述模式使用原子组(?>...)
和所有格量词++
代替非捕获组(?:...)
和简单量词+
。除了正则表达式引擎在原子组和所有格量词失败时无法返回测试其他方式外,其他方式相同,因为它不记录回溯位置。您可以通过此类功能赢得性能。
尝试:
/([a-z0-9]+):([a-z0-9]+)(?:\r\n)?/
或者
/(\w+):(\w+)(?:\r\n)?/
我认为你需要:
/([^:]+):([^\\r\\n]+)/
//__^ note the colon