Java 第1组未按正则表达式匹配
我希望: --输入-- 成为: --输出-- 但是,我不知道如何匹配所有内容,直到“----删除下面的内容”--这样我才能对内容进行分组并删除除上述预期输出之外的所有内容Java 第1组未按正则表达式匹配,java,regex,Java,Regex,我希望: --输入-- 成为: --输出-- 但是,我不知道如何匹配所有内容,直到“----删除下面的内容”--这样我才能对内容进行分组并删除除上述预期输出之外的所有内容 String text = "keep this\n \n" + " keep this too\n ------ Remove Below ------\n remove all of this\n"; Pattern PATTERN = Pattern.co
String text = "keep this\n \n"
+ " keep this too\n ------ Remove Below ------\n remove all of this\n";
Pattern PATTERN = Pattern.compile("^(.*)(-+)(.*)Remove Below(.*)(-+)(.*)$",
Pattern.MULTILINE | Pattern.DOTALL);
Matcher m = PATTERN.matcher(text);
if (m.find()) {
int count = m.groupCount();
String g0 = m.group(0);
String g1 = m.group(1); // contains "keep this\n \n keep this too\n -----"
String g2 = m.group(2);
//
// How can I group correctly to arrive at above expected -- Output --??
//
}
使您的正则表达式
非贪婪
:
Pattern PATTERN = Pattern.compile("^(.*?)(-+)(.*?)Remove Below(.*?)(-+)(.*)$",
Pattern.DOTALL);
另外,模式。在您的案例中不需要多行
现在m.group(1)
将为您提供:
keep this\n \n keep this too\n
您可以使用检查索引“------Remove Below------”然后在该索引或之前取子字符串 将字符串拆分为字符串数组,每行作为一个数组项
String[] split = s.split("\n");
循环遍历此数组并构造一个字符串,直到项匹配------删除以下内容------
字符串结果=”;
对于(int i=0;i
也可以这样做。那(+)表示什么。它后面跟着+?@anubhava:谢谢你的回答。是的,这起作用了。你能解释一下“----”部分是如何在group1中出现的吗?是贪婪回溯的情况吗?这是贪婪匹配的情况。贪婪匹配的情况。(.*)你有(*)
匹配您要匹配的文本和除一个连字符以外的所有连字符。下一组(+)
只匹配单个连字符
。使用非贪婪量词(+)
匹配所有连字符,组1只获得您想要的部分。
keep this\n \n keep this too\n
String[] split = s.split("\n");
String result="";
for(int i=0;i<str.length;i++){
if(!str[i].contains(" Remove Below ")){
result = result.concat(str[i]);
}else{
break;
}
}
"^(.*?)(-+)(.*)Remove Below(.*)(-+)(.*)$"