Remove more than two consecutive occurrence
I have a java String
like this
String str="&P;&P;&P;&P;&P;&P;&P;&P;&P;&P;&P;&P; Tannay Mnadal &P;&P;&P;&P;&P;&P; Tata"
I am trying to remove all &P;
where the consecutive occurrence is more than two.
ie. any function(str)
, will return "&开发者_Go百科;P;&P;" Tannay Mnadal &P;&P; Tata
Any help will be appreciated. Thanks
str = str.replaceAll("&P;&P;(&P;)+", "&P;&P;");
Use a regular expression with replaceAll()
Something like:
str.replaceAll("(&P;){3,}", "&P;&P;");
You can try using a regex replace:
public String function(String str)
{
return str.replaceAll("&P;&P;(&P;)+", "&P;&P;");
// I understood you wanted to keep two times "&P;"
}
You can achieve what you want with regular expressions easily:
public String removeOcurrences(String input) {
return input.replaceAll("(&P;&P;)(?:&P;)*", "$1");
}
Hope it helps.
Regards.
精彩评论