简体   繁体   English

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

[英]Replacing url in a CSS with CSS Parser and Regex (Java)

I have this requirement that I need to replace URL in CSS, so far I have this code that display the rules of a css file: 我有这个要求,我需要在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();
    }

}

However, I am not sure whether how to actually replace the URL since there is not much a documentation about CSS Parser 但是,我不确定是否如何实际替换URL,因为没有太多关于CSS Parser的文档

Here is the modified for loop: 这是修改后的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.
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM