簡體   English   中英

使用reg-ex提取匹配的字符串

[英]Extract the matched string using reg-ex

我搜索了與Java正則表達式相關的問題,並找到了有關Pattern和Matcher類的信息,以獲得圍繞reg-ex的匹配條件的文本組。

但是,我的要求是不同的。 我希望提取正則表達式表示的實際文本。

例:

Input text: ABC 22. XYZ
Regular expression: (.*) [0-9]* (.*)

使用Pattern和Matcher類(或Java中的任何其他方法),我如何獲得文本“22”? 這是正則表達式表示的文本。

您可以嘗試以下正則表達式1

.*?(\s*\d+\.\s+).*

使用一些圖形工具2 ,您可以看到正則表達式中的組在哪里,即:

Imgur

要在Java中提取該組,請執行以下操作:

String input = "ABC 22. XYZ";

System.out.println(
    input.replaceAll(".*?(\\s*\\d+\\.\\s+).*", "$1")
);  // prints " 22. "

其中$1group #1取代。


筆記

  1. 正則表達式的解釋:

     NODE EXPLANATION ------------------------------------------------------------------ .*? any character except \\n (0 or more times (matching the least amount possible)) ------------------------------------------------------------------ ( group and capture to \\1: ------------------------------------------------------------------ \\s* whitespace (\\n, \\r, \\t, \\f, and " ") (0 or more times (matching the most amount possible)) ------------------------------------------------------------------ \\d+ digits (0-9) (1 or more times (matching the most amount possible)) ------------------------------------------------------------------ \\. '.' ------------------------------------------------------------------ \\s+ whitespace (\\n, \\r, \\t, \\f, and " ") (1 or more times (matching the most amount possible)) ------------------------------------------------------------------ ) end of \\1 ------------------------------------------------------------------ .* any character except \\n (0 or more times (matching the most amount possible)) 
  2. 獲取屏幕截圖的工具是Regexper

您的捕獲組已關閉。

Pattern p = Pattern.compile ("(\\d+\\.?)");
Matcher m = p.matcher ("ABC 22. XYZ");
if (m.find ()) {
  System.out.println  (m.group (1));
}

使用()定義捕獲組 ,稍后可以按組索引從匹配器中檢索。 組0總是匹配。

您的輸入在“22”之后有一個點,但您的正則表達式沒有考慮到這一點。

如果您的輸入中只有一個數字,您可以像這樣提取它:

String number = input.replaceAll(".*?(\\d+).*", "$1");

無論輸入的其余部分是什么,此正則表達式都匹配輸入中任何位置的(第一個)數字(任意長度)。

暫無
暫無

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

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