gpt4 book ai didi

java - 匹配所有出现的 Regex Java

转载 作者:行者123 更新时间:2023-11-30 07:49:47 24 4
gpt4 key购买 nike

我想用 Regex Java API 识别字符串的所有“字-数字-字”序列。

例如,如果我有“ABC-122-JDHFHG-456-MKJD”,我希望输出:[ABC-122-JDHFHG, JDHFHG-456-MKJD]。

String test = "ABC-122-JDHFHG-456-MKJD";

Matcher m = Pattern.compile("(([A-Z]+)-([0-9]+)-([A-Z]+))+")
.matcher(test);
while (m.find()) {
System.out.println(m.group());
}

上面的代码只返回“ABC-122-JDHFHG”。

有什么想法吗?

最佳答案

最后的 ([A-Z]+) 匹配并消耗 JDHFHG,因此正则表达式引擎仅在之后“看到”-456-MKJD第一个匹配,模式不匹配这个字符串剩余部分。

您想获得“整个单词”的重叠匹配。

使用

String test = "ABC-122-JDHFHG-456-MKJD";

Matcher m = Pattern.compile("(?=\\b([A-Z]+-[0-9]+-[A-Z]+)\\b)")
.matcher(test);
while (m.find()) {
System.out.println(m.group(1));
} // => [ ABC-122-JDHFHG, JDHFHG-456-MKJD ]

查看 Java demo

图案细节

  • (?= - 与紧随其后的位置相匹配的正面前瞻开始
    • \\b - 单词边界
    • ( - 捕获组的开始(以便能够获取您需要的值)
    • [A-Z]+ - 1+ ASCII 大写字母
    • - - 连字符
    • [0-9]+ - 1+ 位
    • - - 连字符
    • [A-Z]+ - 1+ ASCII 大写字母
  • ) - 捕获组结束
  • \\b - 单词边界
  • ) - 前瞻构造的结尾。

关于java - 匹配所有出现的 Regex Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48311048/

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