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


Question

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.

1
3
2/11/2011 5:04:48 AM

Accepted Answer

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.

5
2/11/2011 6:40:41 AM

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon