【问题标题】:Matcher.group and Regular Expressions Not extracting full regular expressionMatcher.group 和正则表达式没有提取完整的正则表达式
【发布时间】:2013-11-04 18:16:20
【问题描述】:

我有一个String

String s = "adfgadfbfgadg sa 2419sfgh";

我正在尝试提取子字符串

String substring = "sa 2419sfgh"; 

使用以下正则表达式和代码使用 Pattern 和 Matcher。

formNumberRegex = "[al|sf|sa|sc|nrc|nrc form|doe|doe f|lsi|doe form psd f|doe al f]?[\\s\\-\\.]*[\\d]{3,6}[\\s\\-\\.]*[\\w]{1,4}";
formNumberRegexPattern = Pattern.compile(formNumberRegex);
formNumberMatcher = formNumberRegexPattern.matcher(s);

if (formNumberMatcher.find()) {
    String substring = formNumberMatcher.group();
}

但是,我只是得到

substring = "a 2419sfgh";

我的正则表达式和/或匹配器有什么问题?

【问题讨论】:

    标签: java regex string matcher


    【解决方案1】:

    我立刻注意到:

    [al|sf|sa|sc|nrc|nrc form|doe|doe f|lsi|doe form psd f|doe al f]?
    

    应该是:

    (?:al|sf|sa|sc|nrc|nrc form|doe|doe f|lsi|doe form psd f|doe al f)?
    

    “非捕获组”(?:) 可让您避免将第一部分捕获为初始组。这样,整个表达式就是“match group 0”,就是这样。

    在这里测试:http://regex101.com/r/lS9dT2

    【讨论】:

      【解决方案2】:

      你正在使用character class[...]

      [al|sf|sa|sc|nrc|nrc form|doe|doe f|lsi|doe form psd f|doe al f]
      

      而不是group

      (al|sf|sa|sc|nrc|nrc form|doe|doe f|lsi|doe form psd f|doe al f)
      

      你用的可以写成

      (\\||a|l|s|f|s|a|s|c|n|r|c|n|r|c| |f|o|r|m|d|o|e|d|o|e| |f|l|s|i|d|o|e| |f|o|r|m| |p|s|d| |f|||d|o|e| |a|l| |f)
      

      因此,由于字符类将仅匹配 [...] 中使用的所有字符中的一个字符,它将接受 |als... 等等,而更正版本将只接受由 OR 分隔的一种情况,例如 alsf 等。

      所以将你的正则表达式更改为

      String formNumberRegex = "(al|sf|sa|sc|nrc|nrc form|doe|doe f|lsi|doe form psd f|doe al f)?[\\s\\-\\.]*[\\d]{3,6}[\\s\\-\\.]*[\\w]{1,4}";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-05
        • 1970-01-01
        • 2015-12-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多