gpt4 book ai didi

java - java RegEx 中的非捕获组

转载 作者:行者123 更新时间:2023-11-30 02:27:36 25 4
gpt4 key购买 nike

我已经写了一段代码,但它不能正常工作。在这里您可以找到我的 RegEx、我的输入内容和我期望的输出内容。我正在使用非捕获组,因为我想阅读文本直到得到“捆绑”一词,但我不想将其包含在捕获的组中。但我不知道我做错了什么导致它不起作用。

这是我的代码:

Pattern pattern = Pattern.compile(
"((Bundle\\s+Components)|(Included\\s+Components))\\s+(.*?)(?:Bundle)", Pattern.DOTALL);

Matcher matcher = pattern.matcher(tableInformation);

while (matcher.find()) {

String bundleComponents = matcher.group();
System.out.println(bundleComponents);
}

以下是示例:示例1:

Bundle Components bla blah\blabla?!()\\ANY CHARACTER IS POSSIBLE HERE, EVEN LINEBREAK,blah blah
Bundle Type

示例 2:

 Included Components
blah blah, like above,
Bundle Type

我期望Ex的输出。 1:

Bundle Components bla blah\blabla?!()\\ANY CHARACTER IS POSSIBLE HERE, EVEN LINEBREAK,blah blah

我期望Ex的输出。 2:

Included Components
blah blah, like above,

我得到的 Ex 的输出是什么。 2:

 Bundle Components bla blah\blabla?!()\\ANY CHARACTER IS POSSIBLE HERE, EVEN LINEBREAK,blah blah
Bundle Type

我得到的 Ex 的输出是什么。 2:

Included Components
blah blah, like above,
Bundle Type

最佳答案

在完整匹配中,您可以获得正则表达式所说的所有内容,甚至是非捕获组。您需要获得适当的匹配来摆脱非捕获组。另一种解决方案是使用正向前瞻而不是捕获组。检查下面的正则表达式。我还删除了一些不必要的(IMO)组。

(?:Bundle\s+Components|Included\s+Components)\s+.*?(?=Bundle)

结果只有一个完整的匹配。

Demo

PS:在此解决方案中,还将捕获“Bundle”之前的换行符。

关于java - java RegEx 中的非捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45235698/

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