Rust regex pattern - unrecognized escape pattern

不羁的心 提交于 2020-08-19 16:57:35

问题


I do have following string:

\"lengthSeconds\":\"2664\"

which I would like to match with this regexp:

Regex::new("lengthSeconds\\\":\\\"(\\d+)\\\"")

I even tried this:

Regex::new(r#"lengthSeconds\":\"(\d+)\""#)

but I'm getting this:

regex parse error:
lengthSeconds\":\"(\d+)\"
             ^^
error: unrecognized escape sequence

What's wrong with the regexp pattern?


回答1:


By using r#..#, you treat your string as a raw string and hence do not process any escapes. However, since backslashes are special characters in Regex, the Regex expression itself still requires you to escape backslashes. So this

Regex::new(r#"\\"lengthSeconds\\":\\"(\d+)\\""#)

is what you want.

Alternatively, you could write

Regex::new("\\\\\"lengthSeconds\\\\\":\\\\\"(\\d+)\\\\\"").unwrap();

to yield the same result.

See this example on Rust Playground




回答2:


You only need to escape the \ in the regex and can then use a raw string.

r#"\\"lengthSeconds\\":\\"2664\\""# is a valid regex which matches \"lengthSeconds\":\"2664\"

Playground




回答3:


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\\""#


来源:https://stackoverflow.com/questions/54061078/rust-regex-pattern-unrecognized-escape-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!