繁体   English   中英

Java正则表达式捕获组

[英]Java Regular Expressions Capturing Groups

我想从此字符串拆分宽度和高度

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:到目前为止没有成功的匹配

在最简单的情况下:

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++) -即匹配并捕获数字。

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

尝试类似的方法:

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

该模式是错误的:

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

演示

只需在数字前添加空格:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM