Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用Java编写这个.NET正则表达式组捕获操作?_Java_.net_Regex_Regex Group - Fatal编程技术网

如何用Java编写这个.NET正则表达式组捕获操作?

如何用Java编写这个.NET正则表达式组捕获操作?,java,.net,regex,regex-group,Java,.net,Regex,Regex Group,在.NET中,如果我想将字符序列与描述捕获多次出现的组的模式相匹配,我可以编写如下内容: String input = "a, bc, def, hijk"; String pattern = "(?<x>[^,]*)(,\\s*(?<y>[^,]*))*"; Match m = Regex.Match(input, pattern); Console.WriteLine(m.Groups["x"].Value); //the group "y" occurs 0 o

在.NET中,如果我想将字符序列与描述捕获多次出现的组的模式相匹配,我可以编写如下内容:

String input = "a, bc, def, hijk";
String pattern = "(?<x>[^,]*)(,\\s*(?<y>[^,]*))*";

Match m = Regex.Match(input, pattern);
Console.WriteLine(m.Groups["x"].Value);

//the group "y" occurs 0 or more times per match
foreach (Capture c in m.Groups["y"].Captures)
{
    Console.WriteLine(c.Value);
}
这看起来很简单,但不幸的是,下面的Java代码并不像.NET代码那样做。(这是意料之中的,因为java.util.regex似乎不区分组和捕获。)


有人能解释一下如何使用Java实现同样的功能,而不必重新编写正则表达式或使用外部库吗?

您想要的东西在Java中是不可能的。当同一组已匹配多次时,仅保存该组的最后一次匹配。有关更多信息,请阅读模式文档部分。在java中,
匹配器
/
模式
用于“实时”迭代
字符串

重复的例子:

String input = "a1b2c3";
Pattern pattern = Pattern.compile("(?<x>.\\d)*");
Matcher matcher = pattern.matcher(input);
while(matcher.find())
{
     System.out.println(matcher.group("x"));
}
String input=“a1b2c3”;
Pattern=Pattern.compile(“(?。\\d)*”);
Matcher Matcher=pattern.Matcher(输入);
while(matcher.find())
{
System.out.println(matcher.group(“x”));
}
打印(null,因为*也与空字符串匹配):

c3 无效的 没有:

String input = "a1b2c3";
Pattern pattern = Pattern.compile("(?<x>.\\d)");
Matcher matcher = pattern.matcher(input);
while(matcher.find())
{
     System.out.println(matcher.group("x"));
}
String input=“a1b2c3”;
Pattern=Pattern.compile(“(?。\\d)”);
Matcher Matcher=pattern.Matcher(输入);
while(matcher.find())
{
System.out.println(matcher.group(“x”));
}
印刷品:

a
hijk

null
a1 b2 c3 a1 b2 c3
您可以在Java中使用模式和匹配器类。有点不同。例如,以下代码:

Pattern p = Pattern.compile("(el).*(wo)");
Matcher m = p.matcher("hello world");
while(m.find()) {
  for(int i=1; i<=m.groupCount(); ++i) System.out.println(m.group(i));
}

您正在尝试使用哪个版本的Java?IIRC,您需要Java7来支持命名捕获组。这个问题中的一些答案可能会有所帮助:@RussC JSmith必须使用Java7,因为问题不在于命名组(他实际上能够获得命名组,正如您在印刷品中看到的!)。问题在于我的答案=)
String input = "a1b2c3";
Pattern pattern = Pattern.compile("(?<x>.\\d)");
Matcher matcher = pattern.matcher(input);
while(matcher.find())
{
     System.out.println(matcher.group("x"));
}
a1 b2 c3
Pattern p = Pattern.compile("(el).*(wo)");
Matcher m = p.matcher("hello world");
while(m.find()) {
  for(int i=1; i<=m.groupCount(); ++i) System.out.println(m.group(i));
}
el
wo