如何获取带有星号的组的内容?
例如,我想删除一个逗号分隔的列表,e。 G。 1,2,3,4,5
。
private static final String LIST_REGEX = "^(\\d+)(,\\d+)*$";
private static final Pattern LIST_PATTERN = Pattern.compile(LIST_REGEX);
public static void main(String[] args) {
final String list = "1,2,3,4,5";
final Matcher matcher = LIST_PATTERN.matcher(list);
System.out.println(matcher.matches());
for (int i = 0, n = matcher.groupCount(); i < n; i++) {
System.out.println(i + "\t" + matcher.group(i));
}
}
输出是
true
0 1,2,3,4,5
1 1
我怎样才能得到每一个条目,我。 e. 1
, 2
, 3
, ...?
我正在寻找一个通用的解决方案。这只是一个示范性的例子。
请想象一个更复杂的正则表达式,如 ^\\[(\\d+)(,\\d+)*\\]$
来匹配像 [1,2,3,4 这样的列表,5]
最佳答案
您可以使用 String.split()
。
for (String segment : "1,2,3,4,5".split(","))
System.out.println(segment);
或者你可以用断言重复捕获:
Pattern pattern = Pattern.compile("(\\d),?");
for (Matcher m = pattern.matcher("1,2,3,4,5");; m.find())
m.group(1);
对于您添加的第二个示例,您可以进行类似的匹配。
for (String segment : "!!!!![1,2,3,4,5] //"
.replaceFirst("^\\D*(\\d(?:,\\d+)*)\\D*$", "$1")
.split(","))
System.out.println(segment);
我做了一个 online code demo .我希望这就是您想要的。
how can I get all the matches (zero, one or more) for a arbitary group with an asterisk
(xyz)*
? [The group is repeated and I would like to get every repeated capture.]
不,你不能。 Regex Capture Groups and Back-References说明原因:
The Returned Value for a Given Group is the Last One Captured
Since a capture group with a quantifier holds on to its number, what value does the engine return when you inspect the group? All engines return the last value captured. For instance, if you match the string
A_B_C_D_
with([A-Z]_)+
, when you inspect the match, Group 1 will beD_
. With the exception of the .NET engine, all intermediate values are lost. In essence, Group 1 gets overwritten each time its pattern is matched.
关于java - 获取 Group 与 Asterisk 的匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25858345/