java8正则之根据命名捕获组正则提取文本内容

JDK版本1.8

命名捕获组的形式

(?<name>X) X, as a named-capturing group

命名捕获组应用

@Test
public void namedGroup() {
   Pattern pattern = Pattern.compile("(?<text>.*)");
   Matcher matcher = pattern.matcher("abc");
   if(matcher.matches()){
     //输出abc
     System.out.println(matcher.group("text"));
   }
 }
}

引申

如何在不硬编码groupName的情况下去遍历一个正则中的所有命名组?
通过查看Pattern中的源码可以看到

public final class Pattern
    implements java.io.Serializable
{
	//...
	/**
     * Map the "name" of the "named capturing group" to its group id
     * node.
     */
    transient volatile Map<String, Integer> namedGroups;
    //...
    Map<String, Integer> namedGroups() {
        if (namedGroups == null)
            namedGroups = new HashMap<>(2);
        return namedGroups;
    }
    //...
}

可惜不能直接访问namedGroups()来获取,不过可以利用反射来获取该属性。

遍历命名捕获组正则中的name

  @Test
  public void namedGroups() {
    Pattern pattern = Pattern.compile("(?<text>.*)");
    Matcher matcher = pattern.matcher("abc");
    Map<String, Integer> namedGroups = RegexHelper.namedGroups(pattern);
    if (matcher.matches()) {
      for (Entry<String, Integer> entry : namedGroups.entrySet()) {
        System.out
            .println("groupName:" + entry.getKey() + ",value:" + matcher.group(entry.getKey()));
      }
    }
  }

  public static class RegexHelper {

    private static final Method namedGroups;

    static {
      Method namedGroupsMethod = ReflectionUtils.findMethod(Pattern.class, "namedGroups");
      ReflectionUtils.makeAccessible(namedGroupsMethod);
      namedGroups = namedGroupsMethod;
    }

    public static Map<String, Integer> namedGroups(Pattern pattern) {
      Objects.requireNonNull(pattern, "pattern");
      try {
        return (Map<String, Integer>) namedGroups.invoke(pattern);
      } catch (IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
      }
    }
  }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值