gpt4 book ai didi

Java 正则表达式捕获组

转载 作者:行者123 更新时间:2023-12-02 05:01:28 26 4
gpt4 key购买 nike

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

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

最佳答案

尝试如下:

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

关于Java 正则表达式捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28251701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com