如题。有时候我们解析 html 图片标签,要获取图片的宽高。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GetWidthHeight {
    public static void main(String[] args) {
        String style = "<img src=\"https://codechina.csdn.net/cjw0001/imgfortest/-/raw/4fef1bad8502a080da7f243fbed5eaa3f0ba7e87/kuangfen.png\" style=\"width:577px;height:592px;\" />";
        String regex_width = "width:(?<width>\\d+([.]\\d+)?)px;";
        String regex_height = "height:(?<height>\\d+([.]\\d+)?)px;";
        double imgWidth = 0;
        double imgHeight = 0;
        Pattern pattern = Pattern.compile(regex_width);
        Matcher matcher = pattern.matcher(style);
        if (matcher.find()){
            imgWidth = Double.valueOf(matcher.group("width"));
        }
        matcher = Pattern.compile(regex_height).matcher(style);
        if (matcher.find()){
            imgHeight = Double.valueOf(matcher.group("height"));
        }
        System.out.println(imgWidth);
        System.out.println(imgHeight);
    }
}

运行效果

ip正则提取 java 正则获取img标签java_java