Archer
Archer

Reputation: 111

How do I find multiple substrings from one string using regex in Java?

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!

Upvotes: 0

Views: 2192

Answers (3)

Ted Hopp
Ted Hopp

Reputation: 234847

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]*"

Upvotes: 1

pickypg
pickypg

Reputation: 22332

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);
    }
}

Upvotes: 3

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

try this regex

    Pattern p = Pattern.compile("\\d+,.+?(?= |$)");

Upvotes: 3

Related Questions