简体   繁体   English

Java正则表达式捕获不起作用

[英]Java regex capture not working

I have a regular expression: 我有一个正则表达式:

l:([0-9]+)

This should match this string and return three captures (according to Rubular ) 这应该匹配此字符串并返回三个捕获(根据Rubular

"l:32, l:98, l:234"

Here is my code: 这是我的代码:

Pattern p ...
Matcher m = p.matcher(...);
m.find();
System.out.println(m.groupCount());

This prints out 1 (group) when there are three, so I can only do m.group(1) which will only return 32. 当有三个时,这将打印出1(组),所以我只能执行m.group(1) ,它只会返回32。

Calling Matcher.find finds the next instance of the match, or returns false if there are no more. 调用Matcher.find找到下一个匹配实例,如果没有更多实例,则返回false。 Try calling it three times and see if you have all your expected groups. 尝试调用它三次,看看是否有所有预期的组。

To clarify, m.group(1) is trying to find the first group expression in your regular expression . 为了澄清m.group(1)m.group(1)试图在正则表达式中找到第一个组表达式 You only have one such group expression in your regex, so group(2) would never make sense. 您的正则表达式中只有一个这样的组表达式,因此group(2)毫无意义。 You probably need to call m.find() in a loop until it returns false, grabbing the group result at each iteration. 您可能需要循环调用m.find()直到它返回false,并在每次迭代时获取组结果。

I think it needs to be 我认为这应该是

Pattern p ...
Matcher m = p.matcher(...);
int count = 0;

while(m.find()) {
    count++;
}
System.out.println(count);

find looks for the next match, so using a while loop will find all matches. find查找下一个匹配项,因此使用while循环将查找所有匹配项。

Matcher.find() returns false when there are no more matches, so you can do a while loop whilst getting and processing each group . 当没有更多匹配项时, Matcher.find()返回false,因此您可以在获取和处理每个group同时进行while loop For example, if you want to print all matches, you can use the following: 例如,如果要打印所有匹配项,可以使用以下命令:

    Matcher m;
    Pattern p = Pattern.compile("l:([0-9]+)");
    m = p.matcher("l:32, l:98, l:1234");

    while (m.find()) {
        System.out.println(m.group());
    }

If input string format is fixed you could use following regex 如果输入字符串格式是固定的,则可以使用以下正则表达式

"l:32, l:98, l:234".split("(, )?l:")

Output 输出量

[, 32, 98, 234]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM