Java正则表达式捕获不起作用 [英] Java regex capture not working

查看:130
本文介绍了Java正则表达式捕获不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正则表达式:

l:([0-9]+)

这应匹配此字符串并返回三次捕获(根据 Rubular

This should match this string and return three captures (according to Rubular)

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

这是我的代码:

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

当有三个时,打印出1(组),所以我只能 m.group(1)只会返回32。

This prints out 1 (group) when there are three, so I can only do m.group(1) which will only return 32.

推荐答案

调用 Matcher.find 找到匹配的 next 实例,如果没有,则返回false。尝试调用它三次,看看你是否拥有所有预期的组。

Calling Matcher.find finds the next instance of the match, or returns false if there are no more. Try calling it three times and see if you have all your expected groups.

澄清, m.group(1)正在尝试在正则表达式中找到第一个组表达式 。你的正则表达式只有一个这样的组表达式,所以 group(2)永远不会有意义。您可能需要在循环中调用 m.find(),直到它返回false,在每次迭代时获取组结果。

To clarify, m.group(1) is trying to find the first group expression in your regular expression. You only have one such group expression in your regex, so group(2) would never make sense. You probably need to call m.find() in a loop until it returns false, grabbing the group result at each iteration.

这篇关于Java正则表达式捕获不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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