简体   繁体   中英

Invalid escape sequence with my Regex

I keep getting invalid escape sequence with my Regex

private String mathA = "(\d)[ + ](\d)\\s=\?";

I erased every part of the Regex but no matter what I took out it kept giving me the same error. I want to match "5 + 3 =?" where the 5 and 3 can be any digit.

You have some errors in your expression and code.

First of all, you have to escape backslashes with another backslash. Additionally, you are using a character class [...] , so you if you have [ae aaaa] this will only match ae . So, [ + ] will only match a space or a plus.

You can change your code to this:

private String mathA = "(\\d) [+] (\\d)\\s=\\?";
// or escaping +
private String mathA = "(\\d) \\+ (\\d)\\s=\\?";

Btw, if you want match multiple digits, you can use:

private String mathA = "(\\d+) [+] (\\d+)\\s=\\?";

正则表达式可视化

Java treats the character \\\\ specially in strings. The character is treated as an escape to allow for representing, eg, new lines as \\n . To get a literal backslash in a string, you need to use two back slashes \\\\\\\\ .

The error is occurring because Java sees, for example \\\\d and doesn't know what to do with it.

Also make sure that your \\\\\\\\ becomes \\\\\\\\\\\\\\\\ to get around the fact that regex uses the same escape character to get a literal backslash. Four backlashes in the code = 2 in the string = 1 literal backlash in the match.

Also, ? should not be escaped, you don't want a literal question mark.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM