Java regex

(a(b)*)   匹配规则见下文红色描述 

(a(b*))   直接匹配bbb最长的



Capturing Text in a Group in a Regular Expression

group  is a pair of parentheses used to group subpatterns. For example,  h(a|i)t  matches  hat  or  hit . A group also captures the matching text within the parentheses. For example,
input:   abbc
pattern: a(b*)c
causes the substring  bb  to be captured by the group  (b*) . A pattern can have more than one group and the groups can be nested. For example,
pattern: (a(b*))+(c*)
contains three groups:
group 1: (a(b*))
group 2: (b*)
group 3: (c*)
The groups are numbered from left to right, outside to inside. There is an implicit group 0, which contains the entire match. Here is an example of what is captured in groups. Notice that group 1 was applied twice, once to the input  abb and then to the input  ab . Only the most recent match is captured. Note that when using * on a group and the group matches zero times, the group will not be cleared. In particular, it will hold the most recently captured text. For example,
input:   aba
pattern: (a(b)*)+
group 0: aba
group 1: a
group 2: b
Group 1 first matched ab capturing b in group 2. Group 1 then matched the a with group 2 matching zero bs, therefore leaving intact the previously captured b.

Note: If it is not necessary for a group to capture text, you should use a non-capturing group since it is more efficient. For more information, see Using a Non-Capturing Group in a Regular Expression.

This example demonstrates how to retrieve the text in a group.

CharSequence inputStr = "abbabcd";
String patternStr = "(a(b*))+(c*)";

// Compile and use regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.find();

if (matchFound) {
    // Get all groups for this match
    for (int i=0; i<=matcher.groupCount(); i++) {
        String groupStr = matcher.group(i);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值