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!

3 Answers 3

3

try this regex

    Pattern p = Pattern.compile("\\d+,.+?(?= |$)");
0
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);
    }
}
3
  • This does seem easier, but I have to add some more conditions later making regex more suitable. Thank you though!
    – Archer
    Mar 31, 2013 at 5:20
  • Yout beat me by 4 mins @pickypg Mar 31, 2013 at 5:22
  • 1
    @Archer Then i believe it would be better to add this conditions to the question. So people can keep it in mind before answering. Mar 31, 2013 at 5:23
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]*"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.