gpt4 book ai didi

java - 使用 find() 方法第一个实例不匹配

转载 作者:行者123 更新时间:2023-12-01 14:38:34 25 4
gpt4 key购买 nike

我正在搜索正斜杠之间带有数字的子字符串(例如/n/),但 find() 方法始终传递第一次出现的正则表达式。为什么?我的正则表达式有问题吗?

Pattern p = Pattern.compile("(\\/)(\\d+)(\\/)"); 
Matcher m = p.matcher("A/8/E/5/F/6/G/7/H");
while (m.find()) {
System.out.println(m.group(0));
}

最佳答案

如果您只想打印数字,请使用m.group(2)

System.out.println(m.group(2));

另一个解决方案是使用lookahead and lookbehind

Pattern p = Pattern.compile("(?<=\\/)(\\d+)(?=\\/)");
Matcher m = p.matcher("A/8/E/5/F/6/G/7/H");
while (m.find()) {
System.out.println(m.group(0));
}

关于java - 使用 find() 方法第一个实例不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16230586/

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