簡體   English   中英

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

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

我有這個要求,我需要在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.
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM