使用正則表達式匹配多行文本我正在嘗試使用java來匹配多行文本。當我使用Pattern類的Pattern.MULTILINE修飾符,我可以匹配,但我不能這樣做。(?m).相同的模式(?m)和使用String.matches似乎不起作用。我肯定我錯過了什么,但不知道是什么。我不太擅長正則表達式。這就是我試過的String test = "User Comments: This is \t a\ta \n test \n\n message \n";String pattern1 = "User Comments: (\\W)*(\\S)*";Pattern p = Pattern.compile(pattern1, Pattern.MULTILINE);System.out.println(p.matcher(test).find()); //trueString pattern2 = "(?m)User Comments: (\\W)*(\\S)*";System.out.println(test.matches(pattern2)); //false - why?
3 回答

三國紛爭
TA貢獻1804條經驗 獲得超7個贊
str.matches(regex)
Pattern.matches(regex, str)
true
當且僅當 全輸入序列與匹配器的模式匹配
matcher.find()
true
當且僅當 子序列的輸入序列與匹配器的模式相匹配。
String test = "User Comments: This is \t a\ta \ntest\n\n message \n";String pattern1 = "User Comments: [\\s\\S]*^test$[\\s\\S]*";Pattern p = Pattern.compile(pattern1, Pattern.MULTILINE);System.out.println(p.matcher(test).find()); //trueString pattern2 = "(?m)User Comments: [\\s\\S]*^test$[\\s\\S]*";System.out.println(test.matches(pattern2)); //true
(\\W)*(\\S)*
*
User Comments:
\\W
[^a-zA-Z0-9_]
T
添加回答
舉報
0/150
提交
取消