我如何使用StringUtils或Regular Expression解析它

时间:2014-06-18 20:44:48

标签: java regex

我目前面临的问题

<a href="<a href="http://www.freeformatter.com/xml-formatter.html#ad-output" target="_blank">http://www.freeformatter.com/xml-formatter.html#ad-output</a>">Links</a>

从我正在使用的服务返回。如您所见,这不是有效的HTML。有没有人知道任何工具或正则表达式可以帮助我删除内部标记,将其更改为:

<a href="http://www.freeformatter.com/xml-formatter.html#ad-output">Links</a>

编辑: 该服务并不总是返回freeformatter.com网站。它可以返回任何网站

4 个答案:

答案 0 :(得分:1)

如果标签中的网址或内容发生变化,您可能希望使用更通用的模式:

(<a\\shref=\"\\w.+\")\\s.+>\"(.+</a>)

这基本上将你想要的字符串部分捕获到两个组中;然后可以将其重新组合成一个字符串。这是一个有效的例子:

<强> http://ideone.com/TbOvVa

答案 1 :(得分:0)

在Java中:

String s = "<a href=\"<a href=\"http://www.freeformatter.com/xml-formatter.html#ad-output\" target=\"_blank\">http://www.freeformatter.com/xml-formatter.html#ad-output</a>\">Links</a>;

(你需要在程序中以某种方式将其保存为字符串)

然后:

s = s.replace("<a href=\"", "");
String[] pcs = s.split("http://www.freeformatter.com/xml-formatter.html#ad-output</a>\">");
s = pcs[0] + pcs[1];
s = s.replace(" target=\"_blank\"", "");

在完成所有这些处理后,您将获得正确的参考。

答案 2 :(得分:0)

抓住第一个href =&#34; with .substring(0,8) 然后使用.split(&#34; \&#34;&gt;&#34;,1)并在索引1处使用结果数组。

答案 3 :(得分:0)

解决方案1 ​​

只需使用括号()捕获的正则表达式的分组功能。使用Matcher.group()方法获取匹配的组。

查找&gt;之间的所有匹配项和&lt;并根据您的需要进行组合。

这是正则表达式模式>([^\">].*?)<。请查看debuggexregex101

上的演示

模式描述:

.       Any character (may or may not match line terminators)
[^abc]  Any character except a, b, or c (negation)
X*?     X, zero or more times (Reluctant quantifiers)
(X)     X, as a capturing group

了解更多关于

的信息

示例代码:

String string = "<a href=\"<a href=\"http://www.freeformatter.com/xml-formatter.html#ad-output\" target=\"_blank\">http://www.freeformatter.com/xml-formatter.html#ad-output</a>\">Links</a>";

Pattern p = Pattern.compile(">([^\">].*?)<");
Matcher m = p.matcher(string);

while (m.find()) {
    System.out.println(m.group(1));
}

输出:

http://www.freeformatter.com/xml-formatter.html#ad-output
Links

解决方案2

使用String#replaceAll()正则表达式模式尝试使用(</a>)[^$]|([^^]<a(.*?)>)方法。

模式说明:用双引号替换不在最后的</a>和不在开头的<a.*?>

regex101debuggex

上查找演示

此正则表达式的图示:

enter image description here

示例代码:

String string = "<a href=\"<a href=\"http://www.freeformatter.com/xml-formatter.html#ad-output\" target=\"_blank\">http://www.freeformatter.com/xml-formatter.html#ad-output</a>\">Links</a>";

System.out.println(string.replaceAll("(</a>)[^$]|([^^]<a(.*?)>)", "\""));

输出:

<a href="http://www.freeformatter.com/xml-formatter.html#ad-output">Links</a>