有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java正则表达式捕获组在OR运算符后返回null

Matcher matcher = Pattern.compile("\\bwidth\\s*:\\s*(\\d+)px|\\bbackground\\s*:\\s*#([0-9A-Fa-f]+)").matcher(myString);
if (matcher.find()) {
    System.out.println(matcher.group(2));
}

示例数据: myString = width:17px;background:#555;float:left;将产生null。 我想要的是:

matcher.group(1) = 17
matcher.group(2) = 555

我刚开始在Java上使用正则表达式,有什么帮助吗


共 (2) 个答案

  1. # 1 楼答案

    我建议把事情分开一点

    而不是构建一个大型正则表达式(也许你想在字符串中添加更多规则?)您应该将字符串拆分为多个部分:

    String myString = "width:17px;background:#555;float:left;";
    String[] sections = myString.split(";"); // split string in multiple sections
    for (String section : sections) {
    
      // check if this section contains a width definition
      if (section.matches("width\\s*:\\s*(\\d+)px.*")) {
        System.out.println("width: " + section.split(":")[1].trim());
      }
    
      // check if this section contains a background definition
      if (section.matches("background\\s*:\\s*#[0-9A-Fa-f]+.*")) {
        System.out.println("background: " + section.split(":")[1].trim());
      }
    
      ...
    }
    
  2. # 2 楼答案

    下面是一个有效的例子。在regexp中包含|(or)通常会让人感到困惑,因此我又添加了两个匹配器,以展示我将如何做到这一点

    public static void main(String[] args) {
        String myString = "width:17px;background:#555;float:left";
    
        int matcherOffset = 1;
        Matcher matcher = Pattern.compile("\\bwidth\\s*:\\s*(\\d+)px|\\bbackground\\s*:\\s*#([0-9A-Fa-f]+)").matcher(myString);
        while (matcher.find()) {
            System.out.println("found something: " + matcher.group(matcherOffset++));
        }
    
        matcher = Pattern.compile("width:(\\d+)px").matcher(myString);
        if (matcher.find()) {
            System.out.println("found width: " + matcher.group(1));
        }
    
        matcher = Pattern.compile("background:#(\\d+)").matcher(myString);
        if (matcher.find()) {
            System.out.println("found background: " + matcher.group(1));
        }
    }