[英]Extracting Capture Group Using Regex
我只是想捕獲一個包含在靜態文本中的字符串。 我將舉例說明。 這是我正在使用的字符串...
String idInfo = "Any text up here\n" +
"Here is the id\n" +
"\n" +
"?a0 12 b5\n" +
"&Edit Properties...\n" +
"And any text down here";
或以精美的印刷品...
Any text up here
Here is the id
?a0 12 b5
&Edit Properties...
And any text down here
我正在使用以下代碼嘗試打印ID號...
Pattern p = Pattern.compile("Here is the id\n\n\?[a-z0-9]{2}( [a-z0-9]{2}){2}\n&Edit Properties...);
Matcher m = p.matcher(idInfo);
String idNum = m.group(1);
System.out.println(idNum);
而且我只想輸出ID號,所以我希望在此示例中輸出的是...
a0 12 b5
但是,運行代碼時出現“找不到匹配項”異常。 我究竟做錯了什么? 有沒有更簡單,更優雅的方法來完成我的解決方案?
您需要先讓Matcher find
匹配項,然后再使用它。 因此,在訪問m.group(1);
之前,先調用m.find()
(或m.matches()
取決於您的目標m.group(1);
。 還要檢查是否實際找到匹配項(如果m.find()
重新設置為true
),以確保組1存在。
另一件事是代表您的正則表達式的字符串不正確。 你想逃跑?
在正則表達式中,您需要將\\
寫為兩個"\\\\"
因為\\
是String中的特殊字符(例如,用於創建\\n
),這也需要轉義。
您在注釋中指出的最后一件事是( [a-z0-9]{2})
不會在組1中放置匹配a0 12 b5
。要解決此問題,我們需要將[a-z0-9]{2}( [a-z0-9]{2}){2}
括起來。
所以也許
Pattern p = Pattern.compile("Here is the id\n\n\\?([a-z0-9]{2}( [a-z0-9]{2}){2})\n&Edit Properties...");
Matcher m = p.matcher(idInfo);
if (m.find()) {//or while(m.find())
String idNum = m.group(1);
System.out.println(idNum);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.