I wrote code for matching filepath which have extenstion .ncx ,
pattern = Pattern.compile(\"$(\\\\|\\/)[a-zA-Z0-9_]/.ncx\");
Matcher matcher = pattern.math
try this
$(\\|\\/)[a-zA-Z0-9_]/.ncx
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");