Search code examples
javareplaceall

Meaning of "\\cM?\r?\n" in Java


I got a class for something that I wanted to do in Java and it uses a line

text[i] = text[i].replaceAll("\\cM?\r?\n", "");

I completely understand that command replaceAll replaces first string with second one but don't completely understand what "\cM?\r?\n" stands for?

I would appreciate if someone can explain this text between quotes. (I did try to google it but did not find a satisfactory answer)


Solution

  • It's a regular expression.

    \cM matches a Control-M or carriage return character

    \r Matches a carriage return character

    \n is a new line

    ? Matches the preceding character or subexpression zero or one time. For example, "do(es)?" matches the "do" in "do" or "does". ? is equivalent to {0,1}

    Different operating systems have different ways to start a new line in windows its /r/n in POSIX it's different. ec ect.

    Your code is essentially removing all new lines and making everything on one single line.