Java模式匹配器组定义 [英] Java pattern matcher group definition

查看:82
本文介绍了Java模式匹配器组定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的正则表达式,类似于

I have a simple regular expression which looks something like

([a-z]*)( +[a-z]="[0-9]")*

它适用于匹配模式,如

test a="1" b="2" c="3"...

有没有办法在单独的匹配器组中捕获每个名称 - 值对(例如,a =1)?

Is there any way of capturing each of the name-value pairs (e.g., a="1") in a separate matcher group?

正如在上面的例子中,我得到(test)的匹配器组和3个名称 - 值对的唯一匹配器组(即最后一个,c =3) )。我希望有3个匹配组,每对1个。

As it is in the above example, I get a matcher group for (test) and only one matcher group for the 3 name-value pairs (i.e., the last one, c="3"). I would expect 3 matcher groups, 1 for each such pair.

推荐答案


我希望3匹配器每个这样的一对,每组1个。

I would expect 3 matcher groups, 1 for each such pair.

不,它总共是两个组。获得三组键值对的唯一方法是:

No, it's two groups in total. The only way to get the key-value pairs in three groups, is by doing:

([a-z]*)( +[a-z]="[0-9]")( +[a-z]="[0-9]")( +[a-z]="[0-9]")

您可以匹配单个组中的所有键值对,然后使用单独的Pattern&匹配它:

You could match all key value pairs in a single group and then use a separate Pattern & Matcher on it:

import java.util.regex.*;

public class Main {
  public static void main(String[] args) throws Exception {

    String text = "test a=\"1\" b=\"2\" c=\"3\" bar d=\"4\" e=\"5\"";
    System.out.println(text + "\n");

    Matcher m1 = Pattern.compile("([a-z]*)((?:[ \t]+[a-z]=\"[0-9]\")*)").matcher(text);

    while(m1.find()) {

      System.out.println(m1.group(1));

      Matcher m2 = Pattern.compile("([a-z])=\"([0-9])\"").matcher(m1.group(2));

      while (m2.find()) {
        System.out.println("  " + m2.group(1) + " -> " + m2.group(2));
      }
    }
  }
}

产生:

test a="1" b="2" c="3" bar d="4" e="5"

test
  a -> 1
  b -> 2
  c -> 3

bar
  d -> 4
  e -> 5

这篇关于Java模式匹配器组定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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