[英]Java regular expression to capture repetive groups
我無法通過正則表達式捕獲第2組中的所有數據,包括所有字符,數字,空格和特殊字符
嘗試過正則表達式
final String regex = "^:(.*?)//(.*[\\s\\S]?)";
String line1 = ":Humpty Dumpty sat on a wall";
String line2 = "//Humpty Dumpty had a great fall";
String rhyme = line1 + line2+"\n"+ "ssdsds"+"\n";
final String value = rhyme.replaceAll(regex , "$2");
final boolean formatIdentified = rhyme.matches(formatRegex);
System.out.println(formatIdentified);//returns false
我期望的價值
"Humpty Dumpty had a great fall
ssdsds
"
更正后的正則表達式應使用格式:abc//xxxx
,輸出應為xxxx
。
String.replaceAll
和String.matches
完全有可能以不同的方式處理多行字符串的終止符,即換行符與字符串的結尾,這就是為什么value
可以打印預期結果但matches
結果顯示false的原因。
我將更加明確,直接使用Pattern
和Matcher
而不是通過String進行代理:
String rhyme =
":Humpty Dumpty sat on a wall\n" +
"//Humpty Dumpty had a great fall\n" +
"ssdsds\n";
Pattern pattern = Pattern.compile("^:(.*?)//(.*[\\s\\S]?)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(rhyme);
if (matcher.find()) {
System.out.println(matcher.group(2));
} else {
System.out.println("[Pattern not found]");
}
這將輸出:
Humpty Dumpty had a great fall
ssdsds
如果期望只匹配一個新行結尾,則只需將標志更改為Pattern.MULTILINE。
Pattern pattern = Pattern.compile("^:(.*?)//(.*[\\s\\S]?)", Pattern.MULTILINE);
將輸出:
Humpty Dumpty had a great fall
這將提供您想要的輸出。
// ignore everything up to // and then include // and all following
// in capture group 1.
final String regex = ".*(//.*)";
String line1 = ":Humpty Dumpty sat on a wall";
String line2 = "//Humpty Dumpty had a great fall";
String rhyme = line1 + line2 + "\n" + "ssdsds" + "\n";
final String value = rhyme.replaceAll(regex, "$1");
System.out.println(value);
// or the follwing if you want the double quotes.
System.out.println("\"" + value + "\"");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.