2

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.

4

2 回答 2

5

尝试使用正则表达式:

([^;]+)

这应该得到你需要的所有组。

正则表达式 101 演示

于 2013-09-10T10:36:31.983 回答
1

您正在寻找以半列结尾的组。这就是为什么您的正则表达式只计算两组而不是 3 个的原因。您可以使用寻找以每个不是半列的符号开头的组的方法。

([^;]+)

或者您可以在解析输入字符串时使用半列字符或行尾字符:

(.+?)(;|$)

这两种方法都给出了预期的结果。

PS对于第二个,您需要获得第一组以获得预期结果:

System.out.println("group is " + myMatcher.group(1));
于 2013-09-10T10:58:04.300 回答