【问题标题】:simple CSS attributes to HTML parser with java使用java的HTML解析器的简单CSS属性
【发布时间】:2012-12-02 18:06:49
【问题描述】:

我试图解析一个简单的<font> 标记的样式属性并将其转换回简单的html 属性。例如,我有这个字符串 <font style="font-family:tahoma;font-size:24px;color:#9900CC;"> 我想以某种方式将其转换为 <font size="24" color="#9900CC" face="tahoma"> 我知道这可以用正则表达式完成,但我不知道怎么做?

谢谢

【问题讨论】:

  • 你为什么需要那个?
  • 如果您知道如何使用正则表达式,为什么不使用正则表达式?
  • @JanDvorak 你假设replaceAll 不使用正则表达式吗?
  • @RobinVanPersi 除非您仅出于学术目的需要它,或者您解释/提及原因,否则我将坚持“这是一个坏主意。不要那样做。”
  • “因为它不能与...一起正常工作”现在这是我想听到的解释。请不要因为我想听到它而感到冒犯。

标签: java html css regex parsing


【解决方案1】:

所以这是迄今为止我所做的最简单的解决方案,它是一个肮脏的解决方案,但它就像一个魅力:

static public String convertCSSFonttoHTML(String css)
{

    List<List<String>> allFontTags = regexFindMultiStrings("<font[^>]*(style=['\"][^'\"]+['\"])[^>]*>", css);
    String allAttributes = "";

    for(int y=0; y<allFontTags.size(); y++)
    {
        String style = allFontTags.get(y).get(0);
        String size = regexFindString("font-size:([^0-9]+)", style);
        String color = regexFindString("color:([^;]+);", style);
        String face = regexFindString("font-family:([^;]+)", style);

        if(!size.isEmpty())
             allAttributes += "size=\""+size+"\" ";

        if(!color.isEmpty())
             allAttributes += "color=\"" + color + "\" ";

        if(!size.isEmpty())
             allAttributes += "face=\""+face+"\"";



        //do replacements to the first occurance
        css = css.replaceFirst(style, allAttributes);

        //empty atts
        allAttributes = "";
    }

    //Log.e("Regex", css);


    return css;

}

【讨论】:

    猜你喜欢
    • 2013-01-14
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2019-01-20
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多