正则表达式不匹配两个分隔符字符
regex not matching two delimiter chars
我有一个很长的字符串,其中包含 url、标题、描述,如下所示:
||url:foo||title:Books|Pencils||description:my description||
数据始终以 ||
开始和结束
如何匹配 可能 包含一个 |
(如上例所示)但不包含两个 ||
的标题 (Books|Pencils
) ] ?
我试过这样的规则(使用 php preg_match):
#\|\|title:(.*)([\|\|])(.*)#
我猜,
(?<=\|\|title:).*?(?=\|\|)
可能只是那样做。
RegEx Demo 1
如果你想得到另外两个,
(?<=\|\|\burl:|\btitle:|\bdescription:).*?(?=\|\|)
RegEx Demo 2
测试
$re = '/(?<=\|\|\burl:|\btitle:|\bdescription:).*?(?=\|\|)/m';
$str = '||url:foo||title:Books|Pencils||description:my description||';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
输出
array(3) {
[0]=>
array(1) {
[0]=>
string(3) "foo"
}
[1]=>
array(1) {
[0]=>
string(13) "Books|Pencils"
}
[2]=>
array(1) {
[0]=>
string(14) "my description"
}
}
如果您希望 simplify/update/explore 表达式,regex101.com. You can watch the matching steps or modify them in this debugger link, if you'd be interested. The debugger demonstrates that how a RegEx engine 右上面板已说明可能会逐步使用一些示例输入字符串并执行匹配过程。
我有一个很长的字符串,其中包含 url、标题、描述,如下所示:
||url:foo||title:Books|Pencils||description:my description||
数据始终以 ||
如何匹配 可能 包含一个 |
(如上例所示)但不包含两个 ||
的标题 (Books|Pencils
) ] ?
我试过这样的规则(使用 php preg_match):
#\|\|title:(.*)([\|\|])(.*)#
我猜,
(?<=\|\|title:).*?(?=\|\|)
可能只是那样做。
RegEx Demo 1
如果你想得到另外两个,
(?<=\|\|\burl:|\btitle:|\bdescription:).*?(?=\|\|)
RegEx Demo 2
测试
$re = '/(?<=\|\|\burl:|\btitle:|\bdescription:).*?(?=\|\|)/m';
$str = '||url:foo||title:Books|Pencils||description:my description||';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
输出
array(3) {
[0]=>
array(1) {
[0]=>
string(3) "foo"
}
[1]=>
array(1) {
[0]=>
string(13) "Books|Pencils"
}
[2]=>
array(1) {
[0]=>
string(14) "my description"
}
}
如果您希望 simplify/update/explore 表达式,regex101.com. You can watch the matching steps or modify them in this debugger link, if you'd be interested. The debugger demonstrates that how a RegEx engine 右上面板已说明可能会逐步使用一些示例输入字符串并执行匹配过程。