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
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
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With