[英]Regex match for string literal including escape sequence
對於普通的字符串文字(“ hello”),這工作得很好。
"([^"]*)"
但是我也想讓我的正則表達式匹配“ hell \\”這樣的文字,這是我本來可以解決的,但它不起作用。
("(?=(\\")*)[^"]*")
在這里,我嘗試了<\\“>。
怎么樣
Pattern.compile("\"((\\\\\"|[^\"])*)\"")//
^^ - to match " literal
^^^^ - to match \ literal
^^^^^^ - will match \" literal
要么
Pattern.compile("\"((?:\\\\\"|[^\"])*)\"")//
如果您不想添加更多捕獲組。
此正則表達式在引號之間接受\\"
或任何非"
。
演示:
String input = "ab \"cd\" ef \"gh \\\"ij\"";
Matcher m = Pattern.compile("\"((?:\\\\\"|[^\"])*)\"").matcher(input);
while (m.find())
System.out.println(m.group(1));
輸出:
cd
gh \"ij
使用此方法:
"((?:[^"\\\\]*|\\\\.)*)"
[^"\\\\\\\\]*
現在也不再匹配\\
,但是在另一種替換方式中,您將匹配任何轉義字符。
試試這個:
Pattern pattern = Pattern.compile("((?:\\\"|[^\"])*)");
\\\\\\"
匹配\\"
或,
[^\\"]
匹配"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.