Rilcon42
Rilcon42

Reputation: 9763

java combining regex issue

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

Upvotes: 0

Views: 70

Answers (1)

fge
fge

Reputation: 121720

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.

Upvotes: 2

Related Questions