0

I have an expression that I am trying to match the format for using regex. Some of it works, but not all. This works:

String i="3-3";
if(i.matches("[\\d]"+"-"+"[\\d]"))
    System.out.println("correct!");

This does not:

String i="3-3,2-3";
if(i.matches("[\\d]"+"-"+"[\\d]{1+}"))
    System.out.println("correct!");

{1+} tries to guarantee at least one instance (ex: 3-4), but it does not work.

My eventual goal is to write a regex expression that can recognize any combination of numbers like this (the numbers could be any positive integer (assumed). The second number will always be larger than the first. The pairs could include letters and should be in ascending order):

"3-4,5-7C,9-22,22A-27", etc
1
  • Regexes cannot guarantee the "ascending order" part. Also, is 1A-2B legal in your book? Commented Jan 5, 2013 at 4:56

1 Answer 1

2

First of all, you don't need to have a character class ([]) for \d.

Second, a quantifier (by the way {1+} is illegal, you probably meant {1,} which is equivalent to +) applies to the immediately preceding atom, which, in your regex, is [\d] (and again, the brackets are not necessary here).

Third, you cannot guarantee the ascending order part with a regex.

Given your sample data and the expected results, the closest to what you want is this (anchors omitted since you use the [misnamed] .matches() method):

\d+[A-Z]*-\d+[A-Z]*(,\d+[A-Z]*-\d+[A-Z]*)*

(of course, double all backslashes in a Java string).

Finally, if you use this regex often, consider using a Pattern.

Sign up to request clarification or add additional context in comments.

4 Comments

both of ours choke on this: "AAA1-2" -- "AAA1-2".match(/\d+[A-Z]*-\d+[A-Z]*(,\d+[A-Z]*-\d+[A-Z]*)*/) ["1-2", undefined] and "AA1-2".match(/(?:[\dA-Z]{1,2}(?:-[\dA-Z]{1,2})?,?)+$/) ["AA1-2"]
No. Remember that he uses String's .matches() method, which anchors the regex both at the beginning and at the end. Yes, Java has made a fatal mistake of method naming here :(
@fge Thank you for your help. In several of the tutorials I read it stated that + meant 1 or more. I know this way did not work, but why is {1+} wrong in this case?
@Rilcon42 because the {} quantifier takes integers as arguments ({n} for exactly n times, {n,m} for at least n times and at most m times, and {n,} for at least n times and no upper bound). In fact, all standard quantifiers can be rewritten using this: * is {0,}, ? is {0,1} and + is {1,}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.