Ohad Benita
Ohad Benita

Reputation: 543

Regular expression to parse two numbers from a line

What I want to achieve is actually quite simple : I have lines that look similar to :

V123,V20  
10,9999  
100,V220  

etc...

Basically many pairs of numbers with a leading letter / zero. I want to be able to parse them using RegEx, what I've found so far in Java is :

Pattern p = Pattern.compile(".*([1-9](?:\\d{0,2})).*",Pattern.MULTILINE);
Matcher m = p.matcher("V999,V50");
System.out.println(m.matches()); - return true
System.out.println(m.groupCount()); --> this one returns 0

Any help will be appreciated, Thanks.

Upvotes: 0

Views: 206

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

I would do it this way

    Matcher m = Pattern.compile("\\d+").matcher(str);
    while(m.find()) {
        int i = Integer.parseInt(m.group());
    }

Upvotes: 0

Igor Deruga
Igor Deruga

Reputation: 1546

public static void main(String[] args) throws IOException {
    String[] a = new String[] {"V123,V20", "10,9999", "100,V220"};

    for (String s: a) {
        Pattern p = Pattern.compile("[\\D0]*(\\d*)[\\D0]*(\\d*)",Pattern.MULTILINE);
        Matcher m = p.matcher(s);
        System.out.println(m.matches());
        System.out.println(m.group(1) + ", " + m.group(2));
    }
}

Hope it helps!

EDIT

P.S.: if you have trailing letters, you can add \\D in the end:

"[\\D0]*(\\d*)[\\D0]*(\\d*)[\\D]*

Upvotes: 1

Related Questions