"Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )" syntax error
I wrote code for matching filepath which have extenstion .ncx ,
pattern = Pattern.compile("$(\\|\/)[a-zA-Z0-9_]/.ncx");
Matcher开发者_StackOverflow中文版 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.
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.
In java \
is a reserved character for escaping. so you need to escape the \
.
pattern=Pattern.compile("$(\\\\|\\/)[a-zA-Z0-9_]/.ncx");
try this
$(\\|\\/)[a-zA-Z0-9_]/.ncx
精彩评论