2

I just want to use the regular expression to match the backslash (\) character, but it throws a PatternSyntaxException:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
 ^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.util.regex.Pattern.<init>(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at helloworld.HelloWorld.main(HelloWorld.java:20)
freedev
  • 25,946
  • 8
  • 108
  • 125
sanmianti
  • 175
  • 2
  • 8
  • 1
    Use `"\\\\"` because you need to escape the java character as well as the regex character . – Arnaud Jun 07 '17 at 08:11
  • Duplicate of https://stackoverflow.com/questions/4025482/cant-escape-the-backslash-with-regex – Pradeep Singh Jun 07 '17 at 08:11
  • You're escaping the escape character, which in again treats the symbol as non-escaped. Try "\\\\". – vegaasen Jun 07 '17 at 08:12
  • 1
    You need two backslashes to get one in a string literal because of Java rules, and by the regex rules you need to follow that backslash with either another one or something else that you are deliberately escaping. So you would either have `"\\\\"` or `"\\x"` for some other `x`. Or even `"\\\x"`. – user207421 Jun 07 '17 at 08:18

1 Answers1

2

You're just trying a regex using only the regex escape character \ (that's why is raised java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \)

Just to be clear, incidentally, the slash \ in Java is also the character used to identify the start of a escaped sequence (java escape characters) and has special meaning to the compiler. So if you want write a slash in a String you have to double it ("\\").

If you want write a regex that search a slash you must escape it, and translating the regex in a Java String you must double the slashes again.

So the regex for slash becomes "\\\\"

freedev
  • 25,946
  • 8
  • 108
  • 125