Domanda

My input string is

String input=" 4313 :F:7222;scott miles:F:7639;Henry Gile:G:3721";

It's a string with semicolon delimiter. It can contain any number of values delimited by semicolon

I want to use Group capture feature in java and capture the below values (i.e : delimited)

         4313 :F:7222
         scott miles:F:7639
         Henry Gile:G:3721

I know I can use split function under Spring class but for some reason I want to use group capture here.

I tried

Matcher myMatcher = Pattern.compile("(.*?);").matcher(input);
while (myMatcher.find()) {
    System.out.println("group is " + myMatcher.group());
}

output is

group is  4313 :F:7222;
group is scott miles:F:7639;

but expected output is

group is  4313 :F:7222
group is scott miles:F:7639
group is Henry Gile:G:3721

I am not getting how to capture the last value after last semicolon and also I want to get rid of semicolon as I mentioned in expected outcome.

È stato utile?

Soluzione

Try using the regex:

([^;]+)

This should get all the groups you require.

regex101 demo.

Altri suggerimenti

You're seeking for group that finishes with semicolumn. That's why your regex mathes just two groups instead of 3 ones. You can use approach that seeking for group that starts with each symbol that is not a semicolumn.

([^;]+)

or you can use semicolumn character or end of line character while parsing input string:

(.+?)(;|$)

Both of these approaches give an expected result.

P.S. For second one you need to get 1st group for expected result:

System.out.println("group is " + myMatcher.group(1));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top