gpt4 book ai didi

java - 为什么此正则表达式中的后视表达式没有 "obvious maximum length"?

转载 作者:行者123 更新时间:2023-11-29 06:08:58 26 4
gpt4 key购买 nike

给定一个包含一定数量的方括号和其他字符的字符串,我想找到所有以左方括号和一定数量的字母开头的右方括号。例如,如果字符串是

] [abc] [123] abc]

我只想找到第二个右括号。

下面的正则表达式

(?<=[a-z]+)\]

会找到第二个右括号,也是最后一个:

] [abc] [123] abc]

因为我只想找到第一个,所以我对正则表达式进行了明显的更改...

(?<=\[[a-z]+)\]

...我得到“后视组在索引 11 附近没有明显的最大长度。”

\[ 只是一个字符,所以看起来明显的最大长度应该是 1 + 第一个表达式中后视组的明显最大长度。给了什么?


预计到达时间:不特定于左括号。

(?<=a[b-z]+)\]

给我同样的错误。 (嗯,在索引 12 处。)

最佳答案

\[ is only a single character, so it seems like the obvious maximum length should be 1 + whatever the obvious maximum length was of the look-behind group in the first expression. What gives?

这就是重点,“第一个表达式中后视组的明显最大长度是多少”是显而易见的。一条重要规则是您不能在后视中使用 +*。这不仅适用于 Java 的正则表达式引擎,而且适用于更多 PCRE 风格的引擎(甚至 Perl 的 (v5.10) 引擎!)。

然而,您可以使用前瞻来做到这一点:

Pattern p = Pattern.compile("(?=(\\[[a-z]+]))");
Matcher m = p.matcher("] [abc] [123] abc]");
while(m.find()) {
System.out.println("Found a ']' before index: " + m.end(1));
}

(即前瞻 (!) 中的捕获组,可用于获取组的 end(...))

将打印:

Found a ']' before index: 7

EDIT

And if you're interested in replacing such ]'s, you could do something like this:

String s = "] [abc] [123] abc] [foo] bar]";
System.out.println(s);
System.out.println(s.replaceAll("(\\[[a-z]+)]", "$1_"));

将打印:

] [abc] [123] abc] [foo] bar]] [abc_ [123] abc] [foo_ bar]

关于java - 为什么此正则表达式中的后视表达式没有 "obvious maximum length"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7679393/

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