regex - 使用 Rust 的正则表达式箱时如何转义转义的正则表达式字符?

标签 regex rust escaping

我有一个包含许多 "\ 转义字符的正则表达式。我一般测试了我的正则表达式,你可以找到 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]);
    }
}

Playground

我的例子的输出是空的,但我期望 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 character U+0023 (#) and a U+0022 (double-quote) character. The raw string body can contain any sequence of Unicode characters and is terminated only by another U+0022 (double-quote) character, followed by the same number of U+0023 (#) characters that preceded the opening U+0022 (double-quote) character.

关于regex - 使用 Rust 的正则表达式箱时如何转义转义的正则表达式字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54912970/

相关文章:

Python re.findall 打印所有模式

powershell - 使用带有 "&"和 "%"的变量时出现引号问题

rust - 使用 "borrowed value does not live long enough"时为 `as_slice`

string - 如何创建带有转义字符的字符串?

python - 如何检查字符串中的 unicode 或转义序列?

java - 如何绕过 "This expression is not supported in the current option setting"错误

Swift-正则表达式查找替换结果的一部分

php - 检查字符串是否以 php 中的特定单词结尾?

c++ - 通过 Rust 中的泛型类型进行编译时算术,类似于 C++?

types - async fn 的类型是什么?