正则表达式:
/([^]+):([^''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的一些实现允许[]
和[^]
分别为"no character">和"any character"。但请记住,这是JavaScript正则表达式风格所特有的。(如果你对这个主题感兴趣,你可以看看这篇文章。
换句话说,[^]
是['s'S]
的快捷方式,因为javascript没有点或单行模式,其中点可以匹配换行符。
因此,要在 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