Java Regex还是XML解析器?

我想删除任何标签,如

hello hello

成为

  

hello hello

如果由于某种原因它正在使用正则表达式,那么最好的方法是什么?现在有人可以帮忙吗?

 (<|</)[:]{1,2}[^]> 

编辑:添加

绝对使用XML解析器。 不应该使用正则表达式来解析* ML

您不应该使用正则表达式来使用像lxml或BeautifulSoup这样的解析器

 >>> import lxml.html as lxht >>> myString = '

hello hello

' >>> lxht.fromstring(myString).text_content() 'hello hello'

这就是为什么你不应该用正则表达式解析html / xml的原因 。

如果你只是试图从一些简单的XML中提取纯文本,那么最好(最快,最小的内存占用)就是在数据上运行for循环:

PSEUDOCODE以下

 bool inMarkup = false; string text = ""; for each character in data // (dunno what you're reading from) { char c = current; if( c == '<' ) inMarkup = true; else if( c == '>') inMarkup = false; else if( !inMarkup ) text += c; } 

注意:如果在解析过程中遇到CDATA,JavaScript或CSS等问题,这将会中断。

所以,总结一下……如果它很简单,就做上面的事情,而不是正则表达式。 如果不是那么简单,请听其他人使用高级解析器。

这是我个人用于java中同样问题的解决方案。 用于此的库是Jsoup: http ://jsoup.org/。

在我的特殊情况下,我不得不打开具有特定值属性的标签。 你看到这个代码反映出来,它不是这个问题的确切解决方案,但可能会让你走上正轨。

  public static String unWrapTag(String html, String tagName, String attribute, String matchRegEx) { Validate.notNull(html, "html must be non null"); Validate.isTrue(StringUtils.isNotBlank(tagName), "tagName must be non blank"); if (StringUtils.isNotBlank(attribute)) { Validate.notNull(matchRegEx, "matchRegEx must be non null when an attribute is provided"); } Document doc = Jsoup.parse(html); OutputSettings outputSettings = doc.outputSettings(); outputSettings.prettyPrint(false); Elements elements = doc.getElementsByTag(tagName); for (Element element : elements) { if(StringUtils.isBlank(attribute)){ element.unwrap(); }else{ String attr = element.attr(attribute); if(!StringUtils.isBlank(attr)){ String newData = attr.replaceAll(matchRegEx, ""); if(StringUtils.isBlank(newData)){ element.unwrap(); } } } } return doc.html(); }