62,616
社区成员
发帖
与我相关
我的任务
分享
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test{
public static void main(String[] args){
String content = "<img alt=\"pic1\" src=\"123.png\" style=\"width:1in;height:1in;vertical-align:middle\"/>";
String regex = "^(?<head><img.*?)(?<style>style\\s*=\\s*\"[^\"]+\")(?<tail>.*)$";
Matcher matcher = Pattern.compile(regex).matcher(content);
if(!matcher.find()){
return;
}
String style = matcher.group("style");
String result = matcher.group("head") + matcher.group("tail");
style = process(style);
result = result.replaceAll("/>$",style + "/>");
System.out.println(result);
}
private static String process(String style){
String regex_width = "width:(?<width>\\d+([.]\\d+)?)in;";
String regex_height = "height:(?<height>\\d+([.]\\d+)?)in;";
Pattern pattern = Pattern.compile(regex_width);
Matcher matcher = pattern.matcher(style);
StringBuffer result = new StringBuffer();
if(matcher.find()){
double width = Double.valueOf(matcher.group("width")) * 72;
result.append(" width=" + width + "px ");
}
matcher = Pattern.compile(regex_height).matcher(style);
if(matcher.find()){
double height = Double.valueOf(matcher.group("height")) * 72;
result.append(" height=" + height + "px ");
}
result.append(style.replaceAll(regex_width,"").replaceAll(regex_height,""));
return result.toString();
}
}