Rust regex pattern - unrecognized escape pattern

前端 未结 3 810
醉话见心
醉话见心 2021-01-21 07:25

I do have following string:

\\\"lengthSeconds\\\":\\\"2664\\\"

which I would like to match with this regexp:

Regex::new(\"lengt         


        
3条回答
  •  借酒劲吻你
    2021-01-21 07:41

    The string you want to match is:

    \"lengthSeconds\":\"2664\"
    

    To make a regular expression that matches exactly this string, you need to escape all characters that have a special meaning in regexes. In this case, it is only the backslash. The regular expression is:

    \\"lengthSeconds\\":\\"2664\\"
    

    To put this regular expressing into a Rust string literal, you need to escape all characters that have a special meaning in Rust string literals. In this case, it's the quote and the backslash. The string literal is thus:

    "\\\\\"lengthSeconds\\\\\":\\\\\"2664\\\\\""
    

    Since this is very hard to read, you should rather put the regex into a raw string literal. For this you need to escape all characters that have a special meaning in Rust raw string literals, which luckily are none. The raw string literal is thus:

    r#"\\"lengthSeconds\\*:\\"2664\\""#
    

提交回复
热议问题