Java 正则表达式捕获组

标签 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 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/

相关文章:

java - 使用 JFrame 时出现字符串数组错误

java - 在spring boot项目中,如何将application.yaml加载到Java Properties中

java - 为什么-1%26 = -1 在 Java 和 C 中,为什么在 Python 中是 25?

javascript - 正则表达式最多允许 10 位数字,后跟一个逗号和另外 3 位数字

python - 模糊正则表达式(例如 {e<=2})在 Python 中的正确用法

mysql - 在 MySQL 中查询具有特定长度的字符串字段

java - Scala 遗传算法 (GA) 库中的模拟二进制交叉 (SBX) 交叉运算符

java - 将值传递给 JLabel

Java正则表达式跨多行提取文本序列

c - malloc 之后是否必须初始化 char* ?