gpt4 book ai didi

java - 具有可变组数的正则表达式?

转载 作者:IT老高 更新时间:2023-10-28 21:12:54 26 4
gpt4 key购买 nike

是否可以创建具有可变数量组的正则表达式?

例如运行后...

Pattern p = Pattern.compile("ab([cd])*ef");
Matcher m = p.matcher("abcddcef");
m.matches();

...我想要类似的东西

  • m.group(1) = "c"
  • m.group(2) = "d"
  • m.group(3) = "d"
  • m.group(4) = "c".

(背景:我正在解析一些数据行,其中一个“字段”正在重复。我想避免这些字段的 matcher.find 循环。)


正如@Tim Pietzcker 在评论中指出的那样,perl6.NET有这个功能。

最佳答案

根据documentation , Java 正则表达式不能这样做:

The captured input associated with a group is always the subsequence that the group most recently matched. If a group is evaluated a second time because of quantification then its previously-captured value, if any, will be retained if the second evaluation fails. Matching the string "aba" against the expression (a(b)?)+, for example, leaves group two set to "b". All captured input is discarded at the beginning of each match.

(强调)

关于java - 具有可变组数的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5018487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com