簡體   English   中英

正則表達式使用結果替換字符串

[英]Regex using result for replace String

我想選擇<h3>之間的所有文本<h3> /h3> < /h3> < 選擇之后,我想用結果替換String的值。 在以下示例中,結果應為“ 基本信息”

String test="<h3>Basic Information</h3> <div>";
test = test.replaceAll("<h3>(.*?)</h3>", "$1");

但是目前的結果是

基本信息< div>

使用正則表達式,您可以執行以下操作:

String test="<h3>Basic Information</h3> <div>";
String repl = test.replaceFirst(".*<h3>([^&]+).*/h3> <.*", "$1");
//=> Basic Information

雖然您可以完全避免使用正則表達式,也可以使用String API提取相同的文本。

另外,您可以使用此正則表達式進行匹配:

<h3>([^&]+).*/h3> <

並使用Pattern and Matches API獲取捕獲的#1組。

嘗試這個:

Pattern pattern = Pattern.compile("<h3>(.*)<\\/h3>");
Matcher matcher = pattern.matcher("<h3>Basic Information</h3> <div>");
matcher.find();
StringBuffer sb = new StringBuffer();
matcher.appendReplacement(sb,"$1");
String result = sb.toString();

你之所以不能這樣做,只有replaceFirst那是因為appendTail方法被調用在結束replaceFirst方法。 匹配器會將您未指定的組替換為 ,將您指定的組替換為它們的 ,當然還有不匹配的位,這些位很好,因為沒有為它們創建匹配項,所以它們根本不會被替換。

對於您的查詢:

組0 :<h3>

第一組 :基本信息

組0 :</ h3>

不匹配 :<div>

這只是您可以使用匹配器的一般示例。 當然,如果您只想要特定的組...那么請使用:

matcher.group(1)

暫無
暫無

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

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