3 回答

TA貢獻1829條經驗 獲得超13個贊
對于大多數字符串,您需要允許轉義任何內容(而不僅僅是轉義引號)。例如,你很可能需要允許轉義字符像"\n"和"\t"當然,轉義逃逸:"\\"。
這是一個經常問到的問題,很早以前就已經解決(并優化)了。杰弗里·弗里德爾(Jeffrey Friedl)在他的經典著作《精通正則表達式》(第3版)中深入探討了這個問題(例如)。這是您要查找的正則表達式:
好:
"([^"\\]|\\.)*"
版本1:工作正常,但效率不高。
更好:
"([^"\\]++|\\.)*"或"((?>[^"\\]+)|\\.)*"
版本2:如果您擁有所有格限定詞或原子組,則效率更高(請參閱:使用原子組方法的sin的正確答案)。
最好:
"[^"\\]*(?:\\.[^"\\]*)*"
版本3:效率更高。實現Friedl的“展開循環”技術。不需要所有格或原子組(即可以在Javascript和其他功能較少的正則表達式引擎中使用。)
這是PHP語法中針對雙引號和單引號子字符串的推薦正則表達式:
$re_dq = '/"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"/s';
$re_sq = "/'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'/s";

TA貢獻1827條經驗 獲得超9個贊
嘗試這樣的正則表達式:
'/"(\\\\[\\\\"]|[^\\\\"])*"/'
(簡短)說明:
" # match a `"`
( # open group 1
\\\\[\\\\"] # match either `\\` or `\"`
| # OR
[^\\\\"] # match any char other than `\` and `"`
)* # close group 1, and repeat it zero or more times
" # match a `"`
以下代碼段:
<?php
$text = 'abc "string \\\\ \\" literal" def';
preg_match_all('/"(\\\\[\\\\"]|[^\\\\"])*"/', $text, $matches);
echo $text . "\n";
print_r($matches);
?>
生產:
abc "string \\ \" literal" def
Array
(
[0] => Array
(
[0] => "string \\ \" literal"
)
[1] => Array
(
[0] => l
)
)
正如您在Ideone上看到的那樣。
- 3 回答
- 0 關注
- 869 瀏覽
添加回答
舉報