[英]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.