java - 获取 Group 与 Asterisk 的匹配项?

标签 java regex string capturing-group

如何获取带有星号的组的内容?

例如,我想删除一个逗号分隔的列表,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 be D_. 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/

相关文章:

java - 使用嵌套 For 循环比较两个字符串数组

java .matches() 不匹配

javascript - 仅从脚本标签中提取 javascript

java - 尝试使用 Jersey Client API 执行 POST 请求时出现“已连接”异常

java - 如何使用 Java 在弹出窗口中显示数组列表的输出?

ruby - 将 UTF-8 空间更改为可使用 RegEx 的空间

sql - 如何查找导致 ORA-01843 : not a valid month when the data volume is huge? 的记录

java - 打印输入 Java 的最后几行

java - "bubble clusters"项目(可拖动性、分组、绘图、合并组)

java - 是否可以将 application.yml 变量放入属性文件中?