匹配组的总数不依赖于目标字符串("foo: a b c d"
,在你的情况下),但在模式上。您的模式将始终有 3 组:
^([^:]+):(:? ([^ ]+))++$
^ ^ ^
| | |
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).
你能做的就是匹配:
^([^:]+):\s*(.*)$
这样你就有了以下匹配项:
- 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));
}
}
}
这将打印:
key=foo, values=[a, b, c, d]