"Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )" syntax error

33,061

Solution 1

Pattern p = Pattern.compile("[/\\\\]([a-zA-Z0-9_]+\\.ncx)$");
Matcher m = p.matcher("\\sample.ncx");
if (m.find())
{
  System.out.printf("The filename is '%s'%n", m.group(1));
}

output:

The filename is 'sample.ncx'

$ anchors the match to the end of the string (or to the end of a line in multiline mode). It belongs at the end of your regex, not the beginning.

[/\\\\] is a character class that matches a forward-slash or a backslash. The backslash has to be double-escaped because it has special meaning both in a regex and in a string literal. The forward-slash does not require escaping.

[a-zA-Z0-9_]+ matches one or more of the listed characters; without the plus sign, you were only matching one.

The second forward-slash in your regex makes no sense, but you do need a backslash there to escape the dot--and of course, the backslash has to be escaped for the Java string literal.

Because I switched from the alternation (|) to a character class for the leading slash, the parentheses in your regex were no longer needed. Instead, I used them to capture the actual filename, just to demonstrate how that's done.

Solution 2

In java \ is a reserved character for escaping. so you need to escape the \.

pattern=Pattern.compile("$(\\\\|\\/)[a-zA-Z0-9_]/.ncx");

Solution 3

try this

$(\\|\\/)[a-zA-Z0-9_]/.ncx
Share:
33,061
Dev.Sinto
Author by

Dev.Sinto

Android programming

Updated on July 24, 2022

Comments

  • Dev.Sinto
    Dev.Sinto almost 2 years

    I wrote code for matching filepath which have extenstion .ncx ,

     pattern = Pattern.compile("$(\\|\/)[a-zA-Z0-9_]/.ncx");
     Matcher matcher = pattern.mather("\sample.ncx");
    

    This shows a invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ ) syntax error pattern. How can I fix it.

  • Nishant
    Nishant about 13 years
    was editing. : ) knew that people will answer quickly. he is looking for OS independent file path I guess.
  • Tim
    Tim about 13 years
    That should probably be $(\\\\|\\/)[a-zA-Z0-9_]/.ncx The first '\' needs to be escaped too.
  • The Scrum Meister
    The Scrum Meister about 13 years
    @tim Thx. updated. The question was edited after i posted my answer (org question only had 1 \).
  • Dev.Sinto
    Dev.Sinto about 13 years
    @The Scrum Meister Thanks for the quick reply.but it is not matched with a/f/sample.ncx ???
  • The Scrum Meister
    The Scrum Meister about 13 years
    @kariyachan What are you trying to accomplish? There are multiple things wrong with your regex, $ = end of string, the . is not escaped... Please read a Regex tutorial.
  • Dev.Sinto
    Dev.Sinto about 13 years
    Okay,To get the String that ended with .ncx extenstion
  • The Scrum Meister
    The Scrum Meister about 13 years
    @kariyachan Do you want the filename or the entire path?