0
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 上使用正则表达式,有什么帮助吗?

4

2 回答 2

2

我建议把事情分开一点。

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

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());
  }

  ...
}
于 2012-12-29T16:45:33.623 回答
1

这是一个工作示例。有| (或)在正则表达式中通常令人困惑,所以我添加了两个匹配器来展示我将如何做到这一点。

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));
    }
}
于 2012-12-29T16:47:17.930 回答