[英]Regex pattern matching incorrectly
我有一个正则表达式模式试图匹配一个字符串,但是它做错了,所以我将指出正则表达式模式的部分以及它的作用,希望这次能够正确处理:
~ : the start of the regex pattern
, : trying to match the , at the start of the string
.* : 0 or more of any characters in between
=? : stop at the first match of the rest of the pattern
\. : a period
\" : a quote
/ : a slash
> : arrow right
< : arrow left
~ : end of pattern
码:
$content = ", not good in any manner or degree. See more.\"/><"
$regex = "~,.*=?\.\"/><~";
preg_match_all("/$regex/siU", $content, $matches);
echo "<pre>";
print_r($matches);
echo "</pre>";
错误:
Unknown modifier '/'
Unknown modifier '>'
Unknown modifier '<'
但是据我所知,只有这些[\\ ^ $。|?* +(){}是需要转义的正则表达式元字符。 无论如何,我逃避了/和<,错误消失了,但是这次我得到了一个空数组。
$regex = "~,.*=?\.\"\/\>\<~";
preg_match_all("/$regex/siU", $content, $matches);
echo "<pre>";
print_r($matches);
echo "</pre>";
结果:
Array
(
[0] => Array
(
)
)
谁能告诉我我在做什么错?
您必须转义所有反斜线,并且您要使用两个定界符~
和/
,可以使用以下代码:
$regex = "~,.*=?\\.\"/><~siU";
preg_match_all("$regex", $content, $matches);
您可以使用任何regex在线工具(例如regex101)快速查看此内容
https://regex101.com/r/dT1pQ7/1
顺便说一句,不确定是否要使=
可选,但是=?
使=
为可选。
更新:在第一个匹配项中读到“停止”的注释后,您必须通过添加?
来使用非贪婪运算符 在克里斯说的量词之后才是诀窍,所以.+?
或.*?
是懒惰的或非贪婪的量词,使它们在第一次出现时停止
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.