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+,.+?(?= |$)");
Sign up to request clarification or add additional context in comments.

Comments

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 Comments

This does seem easier, but I have to add some more conditions later making regex more suitable. Thank you though!
Yout beat me by 4 mins @pickypg
@Archer Then i believe it would be better to add this conditions to the question. So people can keep it in mind before answering.
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]*"

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.