除了某些单词之外,Java replaceAll()出现

时间:2014-07-30 21:28:10

标签: java regex

我有正则表达式:

str.replaceAll("(?!<img\ssrc=".*?">)([a-z])", "");

...除了此字符串中的<img>标记正文外,应将所有字母踢出去:

 qwerty <img src="image.jpg"> zxc

但我得< =".">而不是<img src="image.jpg">

如何解决这个问题?

2 个答案:

答案 0 :(得分:6)

选项1:仅一个标记

如果您只有一个图片代码,请将其匹配:匹配是您的新字符串。

Pattern regex = Pattern.compile("<img[^>]+>");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    String ReplacedString = regexMatcher.group();
}

选项2:多个标签

使用此正则表达式:

<img[^>]+>|(.)

此问题是此问题中向"regex-match a pattern, excluding..."

解释的技术的典型案例

交替|的左侧匹配完成<img tags>。我们将忽略这些匹配。右侧匹配并捕获单个字符到组1,我们知道它们是正确的,因为它们与左侧的表达式不匹配。

此程序显示了如何使用正则表达式(请参阅the online demo底部的结果):

String subject = "qwerty <img src=\"image.jpg\"> zxc";
Pattern regex = Pattern.compile("<img[^>]+>|(.)");
Matcher m = regex.matcher(subject);
StringBuffer b= new StringBuffer();
while (m.find()) {
if(m.group(1) != null) m.appendReplacement(b, "");
else m.appendReplacement(b, m.group(0));
}
m.appendTail(b);
String replaced = b.toString();
System.out.println(replaced);

参考

答案 1 :(得分:3)

您的问题出在REGEXP中。我看到的第一件事是你没有正确地逃脱你的字符串:

应该是

(?!<img\\ssrc=\".*?\">)([\\s\\S])

请注意,这是两组之间的空白

无论如何我会说:

[^<]*([^>]*>)[\s\S]*
相关问题