我有一个包含许多 "
和 \
转义字符的正则表达式。我一般测试了我的正则表达式,你可以找到 my working live demo 。我将正则表达式转移到 Rust . 这是一个不起作用的简化示例:
extern crate regex; // 1.1.0
use regex::Regex;
fn main() {
let re = Regex::new(r#"123 \\""(\w+)"#).unwrap();
let test = "123 \"PROPFIND\"";
for cap in re.captures_iter(test) {
println!("{}", &cap[1]);
}
}
我的例子的输出是空的,但我期望 PROPFIND
正则表达式文档将我指向了 raw string文档。我尝试了不同的转义技术,但无法弄清楚我在哪里搞砸了。
最佳答案
你原来的模式需要写成
let re = Regex::new(r#"(\d{1,3}(?:\.\d{1,3}){3}) (\w+|-) (\w+|-) \[(.*?)\] "(\w+) (.*?) (HTTPS?)/([0-9]\.[0-9])" ([0-9]+) ([0-9]+) "(\w+|-)" "(.*?)""#).unwrap();
当前为:
let re = Regex::new(r#"123 "(\w+)""#).unwrap();
简而言之,您的模式中的所有 \\""
都应该看起来像 "
。并确保该模式在 r#"
中和 “#
。
请引用Rust raw string literals reference :
Raw string literals do not process any escapes. They start with the character
U+0072
(r
), followed by zero or more of the characterU+0023
(#
) and aU+0022
(double-quote) character. The raw string body can contain any sequence of Unicode characters and is terminated only by anotherU+0022
(double-quote) character, followed by the same number ofU+0023
(#
) characters that preceded the openingU+0022
(double-quote) character.
关于regex - 使用 Rust 的正则表达式箱时如何转义转义的正则表达式字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54912970/