[英]regex: How to match escaped double quoted strings?
我有如下字符串:
\"Some text inside here. And perhaps special chars including newlines...\" then more text (out here)
我如何简单地匹配并返回转义的双引号之间的内容,而丢弃其余部分?
您不能使用以下模式:
\".*\"
因为“点”与换行符不匹配,除非您使用标志“ s”使“点”与所有字符匹配(包括换行符)
甚至更多的是这种模式将与该示例不匹配:
"this is a quoted text" and "this is another one"
上面的模式将匹配整个字符串,而不是两个带引号的文本。 (因为。*是贪婪的,并且会匹配它可以匹配的最长字符串,在这种情况下为整个字符串。)相反,您应该使用。*? 这会使模式“不愿意”,并且将与它可以匹配的最短字符串匹配。
因此,可以将其与标志“ s”(点匹配全部)一起使用来包装它:
\".*?\"
或使用此:
\"[^"]\"
不需要“ s”标志。 (因为[^“]匹配除”之外的任何内容,其中包括换行符。)
(我对PHP语法不熟悉,因此您应该注意应用标志并自己转义字符。)
我假设字符串中只有两个转义的双引号
match = s.match(/\\"(.*)\\"/m)
match[1] if match
这应该适合您:
b'\\".*?\\"'
也可以不用正则表达式来完成:
$str = '\"Some text inside here. And perhaps special chars including newlines...\" then more text (out here)';
$out = explode('"', $str);
echo $out[0]; // outputs "\"
echo $out[1]; // outputs "Some text... ...\"
echo $out[2]; // outputs " then...here)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.