java - 使用 CSS Parser 和 Regex (Java) 替换 CSS 中的 url

标签 java css regex

我有这个要求,我需要替换 CSS 中的 URL,到目前为止,我有这段显示 css 文件规则的代码:

@Override
public void parse(String document) {
    log.info("Parsing CSS: " + document);
    this.document = document;
    InputSource source = new InputSource(new StringReader(this.document));
    try {
        CSSStyleSheet stylesheet = parser.parseStyleSheet(source, null, null);
        CSSRuleList ruleList = stylesheet.getCssRules(); 
        log.info("Number of rules: " + ruleList.getLength());
        // lets examine the stylesheet contents 
        for (int i = 0; i < ruleList.getLength(); i++) 
        { 
            CSSRule rule = ruleList.item(i); 
            if (rule instanceof CSSStyleRule) { 
                CSSStyleRule styleRule=(CSSStyleRule)rule; 
                log.info("selector: " + styleRule.getSelectorText()); 
                CSSStyleDeclaration styleDeclaration = styleRule.getStyle(); 
                //assertEquals(1, styleDeclaration.getLength()); 
                for (int j = 0; j < styleDeclaration.getLength(); j++) {
                    String property = styleDeclaration.item(j); 
                    log.info("property: " + property); 
                    log.info("value: " + styleDeclaration.getPropertyCSSValue(property).getCssText()); 
                    } 
                } 
            } 
    } catch (IOException e) {
        e.printStackTrace();
    }

}

但是,我不确定是否要实际替换 URL,因为关于 CSS Parser 的文档不多。

最佳答案

这是修改后的 for 循环:

//Only images can be there in CSS.
Pattern URL_PATTERN = Pattern.compile("http://.*?jpg|jpeg|png|gif");
for (int j = 0; j < styleDeclaration.getLength(); j++) {
    String property = styleDeclaration.item(j); 
    String value = styleDeclaration.getPropertyCSSValue(property).getCssText();

    Matcher m = URL_PATTERN.matcher(value);
    //CSS property can have multiple URL. Hence do it in while loop.
    while(m.find()) {
        String originalUrl = m.group(0);
       //Now you've the original URL here. Change it however ou want.
    }
}

关于java - 使用 CSS Parser 和 Regex (Java) 替换 CSS 中的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9981698/

相关文章:

java - 获取广告客户 ID 时出错

Java 异步等待 http 重定向

javascript - 如何使用 JavaScript 嵌入 SVG 样式?

javascript - 如何使用regEx删除js中的python注释

sql - 如何使用 sql 更新正则表达式

regex - 如何使用 RegEx 从 HTML 中提取值?

java通过索引+1和-1迭代图像错误模型

java - 如何在固定时间间隔后运行 Camel 计时器,但仅在给定的时间范围内

javascript - 如何确定有效值

html - MS 边缘图形异常