【问题标题】:Print regex matches in java在java中打印正则表达式匹配
【发布时间】:2009-05-07 19:56:50
【问题描述】:

所以我有一个 IP 地址作为字符串。 我有这个正则表达式(\d{1-3})\.(\d{1-3})\.(\d{1-3})\.(\d{1-3}) 如何打印匹配组?

谢谢!

【问题讨论】:

    标签: java regex


    【解决方案1】:
    import java.util.regex.*;
    try {
        Pattern regex = Pattern.compile("(\\d\\{1-3\\})\\.(\\d\\{1-3\\})\\.(\\d\\{1-3\\})\\.(\\d\\{1-3\\})");
        Matcher regexMatcher = regex.matcher(subjectString);
        while (regexMatcher.find()) {
            for (int i = 1; i <= regexMatcher.groupCount(); i++) {
                // matched text: regexMatcher.group(i)
                // match start: regexMatcher.start(i)
                // match end: regexMatcher.end(i)
            }
        } 
    } catch (PatternSyntaxException ex) {
        // Syntax error in the regular expression
    }
    

    【讨论】:

    • 如果您的正则表达式是硬编码的(就像它一样),您不需要捕获 PatternSyntaxException。如果语法有错误,你会在第一次运行程序时发现它。
    • 计数器不应该从 0 开始吗​​?
    【解决方案2】:

    如果你使用 Pattern 和 Matcher 来做你的正则表达式,那么你可以使用 group(int group) 方法询问每个组的 Matcher

    所以:

    Pattern p = Pattern.compile("(\\d{1-3}).(\\d{1-3}).(\\d{1-3}).(\\d{1-3})"); 
    Matcher m = p.matcher("127.0.0.1"); 
    if (m.matches()) {   
      System.out.print(m.group(1));  
      // m.group(0) is the entire matched item, not the first group.
      // etc... 
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2011-03-30
      相关资源
      最近更新 更多