[英]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.