private static final String STYLE_IMG = "url\\s*\\([\"\']?(.+)?[\"\']?\\)";
    private static final Pattern PATTERN_FOR_STYLE_IMG = Pattern.compile(STYLE_IMG,Pattern.CASE_INSENSITIVE);
    public static void main(String[] args){
     String str = "background:url('css/bg.png')\n " +
     "   background:url('css/bg.png')\n"+
     "  background:url('css/bg.png') ";
    
    
     StringBuffer newStyleStr = new StringBuffer();
     Matcher imgMatcher = PATTERN_FOR_STYLE_IMG.matcher(str);
     while(imgMatcher.find()){
     System.out.println("123");  //这样能打印3次,   也就是3个URL都解析到了
     }
     //imgMatcher.appendTail(newStyleStr);
private static final String STYLE_IMG = "url\\s*\\([\"\']?(.+)?[\"\']?\\)";
    private static final Pattern PATTERN_FOR_STYLE_IMG = Pattern.compile(STYLE_IMG,Pattern.CASE_INSENSITIVE);
    public static void main(String[] args){
     String str = "background:url('css/bg.png')  background:url('css/bg.png') background:url('css/bg.png')";
    
    
     StringBuffer newStyleStr = new StringBuffer();
     Matcher imgMatcher = PATTERN_FOR_STYLE_IMG.matcher(str);
     while(imgMatcher.find()){
     System.out.println("123"); //这样只打印一次   也就是3个URL只解析到一个
     //imgMatcher.appendReplacement(newStyleStr,"url(1)"); 
     }
     //imgMatcher.appendTail(newStyleStr);
高手们看看  

解决方案 »

  1.   


    private static final String STYLE_IMG = "url\\s*\\([\"\']?.+?[\"\']?\\)";
      

  2.   

    "url\\s*\\([\"\']?(.+?)?[\"\']?\\)";标红的地方加一个?,用reluctant模式
    否则在贪婪模式下,右边的括号会一直匹配到最后一个Url的右括号,自然就只有一个匹配
    第一段code之所以能找到3个匹配,是因为回车符\n不匹配".",所以截断了匹配,才刚好有3个匹配
      

  3.   

    background:url('css/bg.png')  background:url('css/bg.png') background:url('css/bg.png')
    贪婪模式会认为这是一个匹配
      

  4.   

    "url\\s*\\([\"\']?([^\"\']+)?[\"\']?\\)"中间的(.+)?会匹配所有字符
    API对.的定义是这样的
    .   任何字符(与行结束符可能匹配也可能不匹配) 
    所有\n没有匹配直接断掉
    我吧(.+)? 改成([^\"\']+)? 不包含‘、“
    所有找到下一个’会停住