2

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

DominikM
  • 1,042
  • 3
  • 16
  • 32
  • You could just use OR and groups: `(\d+)|([a-zA-Z]+)` [demo](http://regex101.com/r/yB0iS6) – HamZa Jun 21 '13 at 09:35
  • 1
    Also named groups may be interesting, since I'm not a java dev, take a look at this [answer](http://stackoverflow.com/a/415635/) – HamZa Jun 21 '13 at 09:36

3 Answers3

6

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
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
2

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
    }
}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
1

Here you go:

        String a = "abc,123,abs12,12ab";
        ArrayList<String> numbers = new ArrayList<>();
        ArrayList<String> letters = new ArrayList<>();
        String ar[] = (a.split(","));
        for (String string : ar) {
            try{
                Long.parseLong(string);
                numbers.add(string);
            }catch(NumberFormatException ex){
                letters.add(string);
            }
        }

Above solution handles the cases where integer digit can be at any location in the string. Not only at the beginning or at the end.

ajay.patel
  • 1,957
  • 12
  • 15