开发者

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜