簡體   English   中英

Java使用正則表達式查找和替換字符串

[英]Java Find and Replace String using Regex

我需要以正則表達式格式指定查找字符串 ,以便無論其格式是<html >還是<html>< html>都可以找到head標記。 如何以正則表達式格式指定查找字符串?

String source = "<html >The quick brown fox jumps over the brown lazy dog.</html >";
String find = "<html>";
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);

盡管您可以通過<\\\\s*html\\\\s*> ,但您不應使用正則表達式處理HTML。 強制性鏈接

\\\\s*表示0或多個空格。

不要嘗試使用正則表達式來解析HTML! 嘗試閱讀有關XPath 很有幫助。 盡管XPath默認會嘗試驗證您的文檔,但是您可以嘗試使用HtmlCleaner使其有效。

要提取標簽內的文本,請使用類似

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.

但是,請嘗試避免通過正則表達式解析html。 閱讀本主題

這個例子可能對您有幫助。

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM