0

I want to find every instance of a number, followed by a comma (no space), followed by any number of characters in a string. I was able to get a regex to find all the instances of what I was looking for, but I want to print them individually rather than all together. I'm new to regex in general, so maybe my pattern is wrong?

This is my code:

String test = "1 2,A 3,B 4,23";
Pattern p = Pattern.compile("\\d+,.+");
Matcher m = p.matcher(test);
while(m.find()) {
  System.out.println("found: " + m.group());
}

This is what it prints:

found: 2,A 3,B 4,23

This is what I want it to print:

found: 2,A
found: 3,B
found: 4,23

Thanks in advance!

Archer
  • 111
  • 3
  • 10

3 Answers3

3

try this regex

    Pattern p = Pattern.compile("\\d+,.+?(?= |$)");
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
3

You could take an easier route and split by space, then ignore anything without a comma:

String values = test.split(' ');

for (String value : values) {
    if (value.contains(",") {
        System.out.println("found: " + value);
    }
}
pickypg
  • 22,034
  • 5
  • 72
  • 84
1

What you apparently left out of your requirements statement is where "any number of characters" is supposed to end. As it stands, it ends at the end of the string; from your sample output, it seems you want it to end at the first space.

Try this pattern: "\\d+,[^\\s]*"

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521