[問題] Regular Expressions Pattern的Capturing Groups問題

看板java作者 (Wei-Tse,Hsu)時間2年前 (2021/08/04 20:18), 2年前編輯推噓3(306)
留言9則, 3人參與, 2年前最新討論串1/1
大家好,我是Java的菜雞,目前在學到Regular Pattern的地方 想請問正規表達式的問題,程式碼如下: import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { public static void main( String args[] ) { // String to be scanned to find the pattern. String line = "This order was placed for QT3000! OK?"; String pattern = "(.*)(\\d+)(.*)"; // Create a Pattern object Pattern r = Pattern.compile(pattern); // Now create matcher object. Matcher m = r.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(0) ); System.out.println("Found value: " + m.group(1) ); System.out.println("Found value: " + m.group(2) ); }else { System.out.println("NO MATCH"); } } } 我想請問的是Output的部分 Found value: This order was placed for QT3000! OK? Found value: This order was placed for QT300 Found value: 0 為什麼"(.*)(\\d+)(.*)"; 的m.group(1)是 This order was placed for QT300 就我目前的理解在API裡面查到的內容為 . Any character (may or may not match line terminators) X* X, zero or more times X+ X, one or more times \d A digit: [0-9] .是任何字元、\\d是數字 那麼digit不是從3開始到300,也就是 m.group(1):This order was placed for QT m.group(2):3000 m.group(3):! OK? 為什麼跟我想的不一樣,是我誤會(.*)(\\d+)(.*)的意思嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.165.119.107 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/java/M.1628079531.A.30C.html

08/04 20:33, 2年前 , 1F
要搭配服用.find()和.matches() 等method的文件服用
08/04 20:33, 1F

08/05 13:20, 2年前 , 2F
String pattern = "(.*?)(\\d+)(.*)";
08/05 13:20, 2F

08/05 13:22, 2年前 , 3F
加個問號 就是你要的結果
08/05 13:22, 3F

08/05 13:22, 2年前 , 4F
你可以下 regex greedy 這兩個關鍵字去查資料
08/05 13:22, 4F

08/05 16:27, 2年前 , 5F
.是任何字元,不就包含數字,300可以是.*的部分也可以是\d+
08/05 16:27, 5F

08/05 16:37, 2年前 , 6F
的部分啊,你要先意識到這點再看下去
08/05 16:37, 6F

08/05 16:40, 2年前 , 7F
再來才是300會歸給哪部分,就是2樓提的比對模式的差別
08/05 16:40, 7F

08/05 16:45, 2年前 , 8F
但是如果你的原意是前面的.*只包含非數字部分,何不一開始
08/05 16:45, 8F

08/05 16:45, 2年前 , 9F
就排除數字,不要用.*,用\D*
08/05 16:45, 9F
十分感謝你們的回覆,我了解了! ※ 編輯: d0068267 (1.165.114.83 臺灣), 08/06/2021 00:40:59
文章代碼(AID): #1X2eMhCC (java)
文章代碼(AID): #1X2eMhCC (java)