Java使用Regex查找和替换字符串

时间:2012-09-07 12:03:26

标签: java

我需要以Regex格式指定字符串查找,以便无论格式是<html >还是<html>还是{{1},都可以找到head标记}。如何以Regex格式指定查找字符串?

< html>

4 个答案:

答案 0 :(得分:3)

虽然您可以通过<\\s*html\\s*>解决问题,但不应使用正则表达式处理HTML。 Obligatory link

\\s*表示0个或更多空格。

答案 1 :(得分:1)

不要尝试使用正则表达式解析HTML!试着阅读XPath。很有帮助。 虽然XPath默认会尝试验证您的文档,但您可以尝试HtmlCleaner使其有效。

答案 2 :(得分:0)

要在代码中提取文字,请使用

之类的内容
String source = "<html >The quick brown fox jumps over the brown lazy dog.</html >";
System.out.println( source.replaceAll( "^<\\s*html\\s*>(.*)<\\s*\\/html\\s*>$", "$1" ) );
// output is:
// The quick brown fox jumps over the brown lazy dog.

但是尽量避免使用regexp解析html。阅读this topic

答案 3 :(得分:0)

此示例可能对您有所帮助。

String source = "<html >The quick brown fox jumps over the brown lazy dog.</html >";

        String find = "\\<.*?>";
        String replace = "";        
        Pattern pattern = Pattern.compile(find);        
        Matcher matcher = pattern.matcher(source);        
        String output = matcher.replaceAll(replace); 
        System.out.println("Source = " + source);
        System.out.println("Output = " + output);