gpt4 book ai didi

Java正则表达式分组问题

转载 作者:行者123 更新时间:2023-11-29 04:04:42 24 4
gpt4 key购买 nike

我正在尝试找出我遇到的 Java 正则表达式问题。这是 1.6,但我认为这不重要。无论如何...

我将有一些像下面这样的输入数据......

"Blah yadda yidda 44-Barack Obama, this that the other"

"Something here, there 22-Hyphenated-example.  Hi there folks"

基本上我想提取数字后面的所有内容,直到尾随标点符号。在我要提取的两个示例输入中...

"Barack Obama"

"Hyphenated-example"

我不太了解我需要使用的模式。我能得到的最接近的是这个...

"[0-9]{1,2}-([A-Z -]*\\b*)"

然而,这给了我......

"44-Barack Obama"

我的代码是...

Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Blah yadda yidda 44-Barack Obama, this that the other");
if (matcher.find())
// This gives me "44-Barack Obama" but I want "Barack Obama".
System.out.println(matcher.group());

有趣的是,我使用 QuickREx Eclipse 插件来测试这个模式,它返回了正确的值。但是,运行上面的代码不会。

有什么想法吗?

最佳答案

使用 matcher.group(1) 的结果,而不是 matcher.group()。第二种形式返回与前面的 matchesfind 方法匹配的所有内容。第一种形式用于访问正则表达式中的各个捕获组。

关于Java正则表达式分组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/744732/

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