Question

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)

Was it helpful?

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.

OTHER TIPS

It matches all new-line characters. \cM is Windows line endings. \r\n is another way of doing line endings in Windows. \n is the standard Unix line endings.

? means optional.

So match \cM or \r\n or \n which are all types of line endings. Should make everything on a single line...

As I said earlier, in comment...

Character Escapes

\cX matches a control character. E.g: \cm matches control-M.

\r matches carriage return.

\n matches linefeed.

http://www.javascriptkit.com/javatutors/redev2.shtml

Its a regular expression and in your case will remove all new line/line break characters which match the following : \cM will match a Control-M or carriage return character, \r is used to match a carriage return character and \n is used for a new line

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top