Reputation: 13357
I want the following:
-- Input--
keep this
keep this too
------ Remove Below ------
remove all of this
to become:
-- Output --
keep this
keep this too
However, I cannot figure out how to match everything up until "------ Remove Below ------" so that I can group things and remove everything but the above expected output.
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 --??
//
}
Upvotes: 2
Views: 48
Reputation: 2445
"^(.*?)(-+)(.*)Remove Below(.*)(-+)(.*)$"
would also do this.
Upvotes: 1
Reputation: 39
You can use check the index of "------ Remove Below ------" and then take the substring before that index or Split string into a string array with each line as one array item
String[] split = s.split("\n");
Loop through this array and construct a string until the item matches ------ Remove Below ------
String result="";
for(int i=0;i<str.length;i++){
if(!str[i].contains(" Remove Below ")){
result = result.concat(str[i]);
}else{
break;
}
}
Upvotes: 0
Reputation: 785128
Make your regex non-greedy
:
Pattern PATTERN = Pattern.compile("^(.*?)(-+)(.*?)Remove Below(.*?)(-+)(.*)$",
Pattern.DOTALL);
Also Pattern.MULTILINE
isn't needed in your case.
Now m.group(1)
will give you:
keep this\n \n keep this too\n
Upvotes: 2