TeenCoder TeenCoder - 9 months ago 55
Java Question

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 [a e 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=\\?";

Regular expression visualization