javastringapache-stringutilsstring-utils

How to manipulate a string in java in below scenario


"\r\n\r\n\r\n\r\nCovered. Coverage is limited to a one-time only 7095 for one outpatien" +
"t in vitro fertilization procedure while you are an 7095 member.  If you receive" +
" 7095s for in vitro fertilization services under an 7095 plan, you will not b" +
"e eligible for in vitro fertilization 7095s under any other 7095 plan. In vit" +
"ro fertilization services are not covered when a surrogate is used.  The in vitr" +
"o procedures must be performed at a medical facility that conforms to the Americ" +
"an College of Obstetricians and Gynecologists’ guidelines for in vitro fertiliza" +
"tion clinics or to the American Society for Reproductive Medicine’s minimal stan" +
"dards for programs of in vitro fertilization. \r\n\r\n\r\n\r\n\r\nIf you have a male partn" +
"er, you must meet all of the following criteria:\r\n•   You and your male partner " +
" have a five-year history of infertility or infertility is related to one or mor" +
"e of the following medical conditions: \r\n–         Endometriosis; \r\n–         Ex" +
"posure in utero to diethylstilbestrol (DES); \r\n–         Blockage or surgical re" +
"moval of one or both fallopian tubes; or \r\n–         Abnormal male factors contr" +
"ibuting to the infertility.\r\n•   You and your male partner have been unable to a" +
"ttain a successful pregnancy through other covered infertility treatments.\r\n\r\n\r\n" +
"\r\n\r\nIf you do not have a male partner, you must meet the following criteria:\r\n• " +
"  You are not known to be otherwise infertile, and\r\n•   You have failed to achie" +
"ve pregnancy following three cycles of physician directed, appropriately timed i" +
"ntrauterine insemination.\r\n\r\n\r\n\r\n\r\nPlease note: These services must have precert" +
"ification.  See Chapter 5: Precertification.\r\nPlease note: Exclusions or limits " +
"that may relate to this 7095 are described in Chapter 6: Services Not Covered" +
" in the section labeled Fertility and Infertility.\r\n\r\n\r\n\r\n"

I want to replace /r/n in above string with empty string with following restrictions. 1. Don't not replace /r/n if its exists only once (Ex: /r/n) 2. Replace if multiple /r/n (Ex: /r/n/r/n/r/n/r/n then replace with empty string.

Example String "\r\n\r\n\r\n\r\nCovered. Coverage is limited to a\r\n one-time only 7095 for one outpatient\r\n\r\n\r\n";

Expected Output: Covered. Coverage is limited to a\r\n one-time only 7095 for one outpatient


Solution

  • I would write something like this:

    my_str = my_str.replaceAll("(\r\n){2,}", "");
    

    Hope that helps.