Java正则表达式捕获组

时间:2015-01-31 12:43:28

标签: java regex string

我想从此String

中分割宽度和高度
String imgStyle = "width: 300px; height: 295px;";
int width = 300; // i want to get this value
int height = 295; // i want to get this value

我尝试了很多正则表达式,但我无法得到它们。

String imgStyle = "width: 300px; height: 295px;";

int imgHeight = 0;
int imgWidth = 0;

Pattern h = Pattern.compile("height:([0-9]*);");
Pattern w = Pattern.compile("width:([0-9]*);");

Matcher m1 = h.matcher(imgStyle);
Matcher m2 = w.matcher(imgStyle);

if (m1.find()) {
    imgHeight = Integer.parseInt(m1.group(2));
}

if (m2.find()) {
    imgWidth = Integer.parseInt(m2.group(2));
}

java.lang.IllegalStateException:到目前为止没有成功匹配

4 个答案:

答案 0 :(得分:1)

在最简单的情况下:

public static void main(String[] args) {
    final String imgStyle = "width: 300px; height: 295px;";
    final Pattern pattern = Pattern.compile("width: (?<width>\\d++)px; height: (?<height>\\d++)px;");
    final Matcher matcher = pattern.matcher(imgStyle);
    if (matcher.matches()) {
        System.out.println(matcher.group("width"));
        System.out.println(matcher.group("height"));
    }
}

只需用(\\d++)替换数字部分即 - 即匹配并捕获数字。

为了清晰起见,我使用了命名组。

答案 1 :(得分:1)

尝试类似:

String imgStyle = "width: 300px; height: 295px;";
Pattern pattern = Pattern.compile("width:\\s+(\\d+)px;\\s+height:\\s+(\\d+)px;");
Matcher m = pattern.matcher(imgStyle);
if (m.find()) {
    System.out.println("width is " + m.group(1));
    System.out.println("height is " + m.group(2));
}

答案 2 :(得分:0)

模式错误:

Pattern h = Pattern.compile("height:([0-9]*);");
Pattern w = Pattern.compile("width:([0-9]*);");

在你的字符串中,冒号和数字之间有一个空格,你在分号前也有px,所以它应该是:

Pattern h = Pattern.compile("height: ([0-9]*)px;");
Pattern w = Pattern.compile("width: ([0-9]*)px;");

或更好:

Pattern h = Pattern.compile("height:\\s+(\\d+)px;");
Pattern w = Pattern.compile("width:\\s+(\\d+)px;");

您还应该捕获第1组,而不是第2组:

if (m1.find()) {
    imgHeight = Integer.parseInt(m1.group(1));
}

if (m2.find()) {
    imgWidth = Integer.parseInt(m2.group(1));
}

DEMO

答案 3 :(得分:0)

只需在数字前添加空格:

Pattern h = Pattern.compile("height:\\s*([0-9]+)");
Pattern w = Pattern.compile("width:\\s*([0-9]+)");