Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>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)); } </code></pre> <p>output:</p> <pre><code>The filename is 'sample.ncx' </code></pre> <hr> <p><code>$</code> <a href="http://www.regular-expressions.info/anchors.html" rel="noreferrer">anchors</a> the match to the end of the string (or to the end of a line in multiline mode). It belongs at the <em>end</em> of your regex, not the beginning.</p> <p><code>[/\\\\]</code> is a <a href="http://www.regular-expressions.info/charclass.html" rel="noreferrer">character class</a> 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 <em>not</em> require escaping. </p> <p><code>[a-zA-Z0-9_]+</code> matches <strong>one or more</strong> of the listed characters; without the <a href="http://www.regular-expressions.info/repeat.html" rel="noreferrer">plus sign</a>, you were only matching <em>one</em>.</p> <p>The second forward-slash in your regex makes no sense, but you do need a backslash there to escape the <a href="http://www.regular-expressions.info/dot.html" rel="noreferrer">dot</a>--and of course, the backslash has to be escaped for the Java string literal.</p> <p>Because I switched from the <a href="http://www.regular-expressions.info/alternation.html" rel="noreferrer">alternation</a> (<code>|</code>) to a character class for the leading slash, the parentheses in your regex were no longer needed. Instead, I used them to <a href="http://www.regular-expressions.info/brackets.html" rel="noreferrer">capture</a> the actual filename, just to demonstrate how that's done.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload