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

私は物事を少し分割することをお勧めします。

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

  ...
}
于 2012-12-29T16:45:33.623 に答える
1

これが実際の例です。持つ | (または) 正規表現では通常混乱するので、2 つのマッチャーを追加して、その方法を示します。

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 に答える