Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract numbers and names from string

Tags:

java

regex

My goal is to extract names and numbers from a string in java. Examples: input -> output

1234 -> numbers: [1234], names: []

1234,34,234 -> numbers: [1234, 34, 234], names: []

12,foo,123 -> numbers: [12, 123], names: [foo]

foo3,1234,4bar,12,12foo34 -> numbers: [1234, 12], names: [foo3, 4bar, 12foo34]

foo,bar -> -> numbers: [], names: [foo, bar]

I came up with [^,]+(,?!,+)* which match all parts of the string, but i dont know how to match only numbers or names (names can contain number - as in example). Thanks

like image 750
DominikM Avatar asked Dec 14 '25 23:12

DominikM


2 Answers

Here's a regex-only solution:

(?:(\d+)|([^,]+))(?=,|$)

The first group (\d+) captures numbers, the second group ([^,]+) captures the rest. A group must be followed by a comma or the end of line (?=,|$).

A quick demo:

Pattern p = Pattern.compile("(?:(\\d+)|([^,]+))(?=,|$)");
Matcher m = p.matcher("foo3,1234,4bar,12,12foo34");

while (m.find()) {
    System.out.println(m.group(1) != null 
        ? "Number: " + m.group(1)  
        : "Non-Number: " + m.group(2));
}

Output:

Non-Number: foo3
Number: 1234
Non-Number: 4bar
Number: 12
Non-Number: 12foo34
like image 56
Lukas Eder Avatar answered Dec 16 '25 12:12

Lukas Eder


You can use a Scanner:

Scanner sc = new Scanner(input);
sc.useDelimiter(",");
while(sc.hasNext()) {
    if(sc.hasNextInt()) {
        int readInt = sc.nextInt();
        // do something with the int
    } else {
        String readString = sc.next();
        // do something with the String
    }
}
like image 23
Jean Logeart Avatar answered Dec 16 '25 12:12

Jean Logeart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!