Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your regex isn't quite right.</p> <p>When you write: <code>[RQrq1-6]*</code></p> <p>You're saying match zero or more repetitions of any character in the square brackets...</p> <p>Try this <code>[RQrq1-6]</code> - which means match exactly one.</p> <p>I wrote a little "spike" program:</p> <pre><code>import java.util.regex.Pattern; public class Spike { public static void main(String[] args) { testIt("Q"); testIt("q"); testIt("z"); testIt("Z"); testIt("R"); testIt("r"); testIt("0"); testIt("1"); testIt("2"); testIt("3"); testIt("4"); testIt("5"); testIt("6"); testIt("7"); testIt("02"); testIt("11"); testIt("17"); testIt(""); // should fail, used to pass with the question's regex } public static void testIt(String sample) { System.out.print(sample+" "); if (Pattern.matches("[RQrq1-6]*", sample)) { System.out.println("match"); } else { System.out.println("fail"); } } </code></pre> <p>}</p> <p>Output was this:</p> <pre><code>Q match q match z fail Z fail R match r match 0 fail 1 match 2 match 3 match 4 match 5 match 6 match 7 fail 02 fail 11 match 17 fail match </code></pre> <p>Having removed the star in the regex:</p> <pre><code>Q match q match z fail Z fail R match r match 0 fail 1 match 2 match 3 match 4 match 5 match 6 match 7 fail 02 fail 11 fail 17 fail fail </code></pre> <p>How to ignore the blanks</p> <p>Substitute this version of testit:</p> <pre><code>public static void testIt(String sample) { System.out.print(sample+" "); Pattern pattern = Pattern.compile("\\s*([RQrq1-6])\\s*"); Matcher matcher = pattern.matcher(sample); if (matcher.matches()) { System.out.println("match '"+matcher.group(1)+"'"); } else { System.out.println("fail"); } } </code></pre> <p>Here are the critical lines of the output: </p> <pre><code>testIt(" 6");// ignore space tests testIt(" 7");// ignore space tests testIt("6 ");// ignore space tests testIt("7 ");// ignore space tests 6 match '6' 7 fail 6 match '6' 7 fail </code></pre> <p>It uses a concept called a "capture group". A capture group is a section of a regex which is assigned a number so that the specific string of symbols that matched can be extracted. We're using a capture group here to pull the symbol out from the optional whitespace.</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