Java 6正则表达式是一组的多个匹配项 [英] Java 6 regex multiple matches of one group

查看:1132
本文介绍了Java 6正则表达式是一组的多个匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的模式: [key]:[value1] [value2] [value3] [valueN]

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

我想得到:


  1. key

  2. 值数组

这是我的正则表达式: ^([^:] +):(:?([^] +))++ $

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

这是我的文字: foo:abcd

Matcher 给了我2组: foo (作为关键)和 d (作为值)。

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

如果我使用 +?而不是 ++ 我得到 a ,而不是 d

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

因此,java首先(或最后一次)发生组返回。

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

我不能使用 find()这里因为只有一个匹配。

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

除了将正则表达式拆分为2部分并使用find作为值数组?
我在许多其他环境中使用正则表达式,几乎所有环境都能够获取第一次出现第1组,第二次出现第1组等等。

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.

如何在JDK6中使用 java.util.regex

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

谢谢。

推荐答案

匹配组的总数不依赖于目标字符串(foo:abcd ,在你的情况下),但在模式上。你的模式总是有3组:

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

1 st 组将保留您的key和2 nd 组,它们与第3组相同但后面包含一个空格,总是只保留1个值。这是第一个值(如果是不合格的 +?)或最后一个值(如果是贪婪的匹配)。

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).

你能做的就是匹配:

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

以便您拥有以下匹配项:

so that you have the following matches:

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

然后将2 nd 组拆分为空白区以获取所有值:

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

将打印:

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

这篇关于Java 6正则表达式是一组的多个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆