我有以下字符串:

background: url('../../footer/right.png') repeat;

background: url("../../footer/left.png") repeat;


我只想提取这样的URL:

../../footer/right.png

../../footer/left.png


到目前为止,我的RegExps是

.*?[(\'|(\"|(|\'|\"](.*?)[\"|\'|)|\")|\')].*?

[[\\(\']([^\']*?)[\'\\)]]|[\\(\"]([^\"]*?)[\"\\)]|[\\(]([^)]*?)[\\)]|[\']([^\']*?)[\']|[\"]([^\"]*?)[\"]


但是它一直给我

背景:url ../../ footer / izquierdo.png重复;

为什么这样做,什么是正确的模式?

编辑

在您的帮助下,我已经找到了答案,但是我不太清楚为什么会起作用

(?<=\\(|\'|\")(.*?)(?=\'|\"|\\))


谁知道为什么它可以匹配( (" (' ' "的任意组合?

顺便说一句,此匹配符合我的逻辑(我没有提过,但确实如此)

谢谢大家的帮助

最佳答案

如何使用类似的东西

\\(('|\")(.*?)\\1\\)


或者甚至在之前添加url

url\\(('|\")(.*?)\\1\\)


\\1表示来自组1的匹配,只能是'"。这里使用它的目的是要确保在括号之后和括号之前有相同类型的引用。

此正则表达式会将../../footer/right.png部分放在组2中,因此您可以使用matcher.group(2)来获取它。



例:

String data = "background: url('../../footer/right.png') repeat;\r\n" +
        "\r\n" +
        "background: url(\"../../footer/left.png\") repeat;";
Pattern p = Pattern.compile("\\(('|\")(.*?)\\1\\)");
Matcher m = p.matcher(data);
while (m.find())
    System.out.println(m.group(2));


输出:

../../footer/right.png
../../footer/left.png

关于java - 正则表达式,用于在括号和/或引号之间捕获文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22413585/

10-11 04:39