开发者

Remove more than two consecutive occurrence

开发者 https://www.devze.com 2023-02-15 13:14 出处:网络
I havea 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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号