Java正则表达式捕获组

Java正则表达式捕获组,java,regex,string,Java,Regex,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

我想从这个字符串中拆分宽度和高度

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

模式错误:

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));
}
在最简单的情况下:

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"));
    }
}
publicstaticvoidmain(字符串[]args){
最终字符串imgStyle=“宽度:300px;高度:295px;”;
最终模式=模式。编译(“宽度:(?\\d++)px;高度:(?\\d++)px;”;
最终匹配器匹配器=pattern.Matcher(imgStyle);
if(matcher.matches()){
System.out.println(匹配器组(“宽度”);
System.out.println(匹配器组(“高度”);
}
}
只需将数字部分替换为
(\\d++)
-即匹配并捕获数字


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

只需在数字前添加空格:

Pattern h = Pattern.compile("height:\\s*([0-9]+)");
Pattern w = Pattern.compile("width:\\s*([0-9]+)");
尝试以下方法:

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

我尝试了很多正则表达式,但都找不到它们
请发布您的尝试,这样我们就可以看到它们并告诉您出了什么问题为什么
\\d++
而不是
\\d++
?@RaviThapliyal这是个问题。防止任何回溯。啊,读得不错。因此,比赛时间越长,任何回溯的表现影响就越大+1.