java 正则匹配多个,Java 6正则表达式是一组的多个匹配项

博客讨论了在Java中使用正则表达式从字符串`foo:abcd`中提取键值对的问题。作者指出,当前的正则表达式只能返回第一个或最后一个匹配值。解决方案是使用更简单的正则匹配,然后通过分割获取所有值。提供的代码示例展示了如何通过改变正则和使用`split()`方法来正确提取键和值数组。
摘要由CSDN通过智能技术生成

Here is simple pattern: [key]: [value1] [value2] [value3] [valueN]

I want to get:

key

array of values

Here is my regex: ^([^:]+):(:? ([^ ]+))++$

Here is my text: foo: a b c d

Matcher gives me 2 groups: foo (as key) and d (as values).

If I use +? instead of ++ I get a, not d.

So java returns me first (or last) occurrence of group.

I can't use find() here becase there is only one match.

What can I do except splitting regex into 2 parts and using find for the array of values?

I have worked with regular expressions in many other environments and almost all of them have ability to fetch "first occurrence of group 1", "second occurrence of group 1" and so on.

How can I do with with java.util.regex in JDK6 ?

Thanks.

解决方案

The total number of match groups does not depend on the target string ("foo: a b c d", in your case), but on the pattern. Your pattern will always have 3 groups:

^([^:]+):(:? ([^ ]+))++$

^ ^ ^

| | |

1 2 3

The 1st group will hold your key, and the 2nd group, which matches the same as group 3 but then includes a white space, will always hold just 1 of your values. This is either the first values (in case of the ungreedy +?) or the last value (in case of greedy matching).

What you could do is just match:

^([^:]+):\s*(.*)$

so that you have the following matches:

- group(1) = "foo"

- group(2) = "a b c d"

and then split the 2nd group on it's white spaces to get all values:

import java.util.Arrays;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Main {

public static void main (String[] args) throws Exception {

Matcher m = Pattern.compile("^([^:]+):\\s*(.*)$").matcher("foo: a b c d");

if(m.find()) {

String key = m.group(1);

String[] values = m.group(2).split("\\s+");

System.out.printf("key=%s, values=%s", key, Arrays.toString(values));

}

}

}

which will print:

key=foo, values=[a, b, c, d]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值