BadCoder
BadCoder

Reputation: 141

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.

Upvotes: 2

Views: 6312

Answers (2)

Federico Piazza
Federico Piazza

Reputation: 30995

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

Upvotes: 2

k_g
k_g

Reputation: 4464

Java treats the character \\ specially in strings. The character is treated as an escape to allow for representing, e.g., 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.

Upvotes: 0

Related Questions