正则表达式模式匹配不正确
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);
您可以使用任何正则表达式在线工具(如 regex101)快速查看此内容
https://regex101.com/r/dT1pQ7/1
顺便说一句,不确定您是否想让 =
可选,但是 =?
使 =
成为可选的。
更新:在第一场比赛中阅读您对 "stop" 的评论后,您必须使用非贪婪运算符,在量词后添加 ?
,正如 Chris 所说的那样,所以 .+?
或 .*?
是惰性或非贪婪量词,在第一次出现时停止
我有一个正则表达式模式试图匹配一个字符串,但它做错了,所以我要指出正则表达式模式的一部分以及它做了什么,希望这次能正确:
~ : 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);
您可以使用任何正则表达式在线工具(如 regex101)快速查看此内容
https://regex101.com/r/dT1pQ7/1
顺便说一句,不确定您是否想让 =
可选,但是 =?
使 =
成为可选的。
更新:在第一场比赛中阅读您对 "stop" 的评论后,您必须使用非贪婪运算符,在量词后添加 ?
,正如 Chris 所说的那样,所以 .+?
或 .*?
是惰性或非贪婪量词,在第一次出现时停止