Java Regex不适用于特殊字符 [英] Java Regex doesn't work with special chars
问题描述
我的解析器出了问题。我想在网站上阅读图像链接,这通常可以正常工作。但今天我得到了一个包含特殊字符的链接,并且通常的正则表达式不起作用。
I got a problem with my parser. I want to read an image-link on a webiste and this normally works fine. But today I got a link that contains special chars and the usual regex did not work.
这就是我的代码的样子。
This is how my code looks like.
Pattern t = Pattern.compile(regex.trim());
Matcher x = t.matcher(content[i].toString());
if(x.find())
{
values[i] = x.group(1);
}
这是html的一部分,会导致麻烦
And this is the part of html, that causes trouble
<div class="open-zoomview zoomlink" itemscope="" itemtype="http://schema.org/Product">
<img class="zoomLink productImage" src="
http://tnm.scene7.com/is/image/TNM/template_335x300?$plus_335x300$&$image=is{TNM/1098845000_prod_001}&$ausverkauft=1&$0prozent=1&$versandkostenfrei=0" alt="Produkt Atika HB 60 Benzin-Heckenschere" title="Produkt Atika HB 60 Benzin-Heckenschere" itemprop="image" />
</div>
这是我用来获取src属性中的部分的正则表达式:
And this is the regex I am using to get the part in the src-attribute:
<img .*src="(.*?)" .*>
我认为它与链接中的所有特殊字符有关。但我不知道如何逃避所有这些。我已经尝试了
I believe that it has something to do with all the special character inside the link. But I'm not sure how to escape all of them. I Already tried
Pattern.quote(content[i].toString())
但结果是一样的:没有找到。
But the outcome was the same: nothing found.
推荐答案
。
字符通常只匹配除换行符之外的所有内容。因此,如果img-tag中有换行符,则您的模式将不匹配。
The .
character usually only matches everything except new line characters. Therefore, your pattern won't match if there are newlines in the img-tag.
使用 Pattern.compile(...,Pattern。 DOTALL)
或用(?s)
添加您的模式。
Use Pattern.compile(..., Pattern.DOTALL)
or prepend your pattern with (?s)
.
在dotall模式下,表达式。匹配任何字符,包括
行终止符。默认情况下,此表达式与行
终止符不匹配。
In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators.
http://docs.oracle.com/javase/1.5.0/docs/api/ java / util / regex / Pattern.html #DOTALL
这篇关于Java Regex不适用于特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!