Alex
Alex

Reputation: 12913

Regex remove carriage return from end of lines if it exists

The data looks like this:

0.43,0.57,0.71,0.29,0.71,1.00,0.57,1.00\r
0.43,0.57,0.71,0.29,0.71,1.00,0.57,1.00
0.43,0.57,0.71,0.29,0.71,1.00,0.57,1.00\r

and I want to extract the carriage return characters (marked with \r in the sample above). I have been trying this using gm and a capture group:

(.*)(?:\\r)$

but this matches only the lines with an \r. I thought the solution would be to add a ? before the $ but this does not work.

demo: https://regex101.com/r/jArLdS/1

Cheers

Upvotes: 5

Views: 11176

Answers (3)

kayleeFrye_onDeck
kayleeFrye_onDeck

Reputation: 6968

Portable solution.

(^.*?)(\\r)(\r\n|\n)

That's 3 capture groups, left-to-right, starting at 1, not 0.

Replace your string with capture groups 1 and 3, skipping 2.

Capture groups usually syntactically like \1 or $1 for most languages that use them.

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

If you want to match all lines excluding \r - a carriage return - use

[^\r\n]+

that is a negated character class ([^...]) that matches one or more (due to + quantifier) characters other than \r and \n.

Upvotes: 4

CMPS
CMPS

Reputation: 7769

Live Demo

Try this regex:

^([^\\r\n]*)(:?\\r)?$

This is assuming you mean excluding the \r and not extracting \r because your original regex does that.

Upvotes: 0

Related Questions