itwb
itwb

Reputation: 437

Regex - remove any number of commas at the end of a line

Alright, Regex gurus, how can I change my logic to fix this one?

I've made a regex:

(,[,]+)

It's supposed to remove extra commas on the end of a line. (end of line being \r\n) when formatted as a string.

It works (sort of).

This is the string:

Date,1-Jul-18,1-Jul-19,1-Jul-20,1-Jul-21,1-Jul-22,1-Jul-23,1-Jul-24,\r\nDate,1-Jul-18,1-Jul-19,1-Jul-20,1-Jul-21,1-Jul-22,1-Jul-23,1-Jul-24,,,,,\r\nDate,1-Jul-18,1-Jul-19,1-Jul-20,1-Jul-21,1-Jul-22,1-Jul-23,1-Jul-24,,,,,\r\nDate,1-Jul-18,1-Jul-19,1-Jul-20,1-Jul-21,1-Jul-22,1-Jul-23,1-Jul-24,,\r\n

When I run that regex, it gives a result of:

Date,1-Jul-18,1-Jul-19,1-Jul-20,1-Jul-21,1-Jul-22,1-Jul-23,1-Jul-24,\r\nDate,1-Jul-18,1-Jul-19,1-Jul-20,1-Jul-21,1-Jul-22,1-Jul-23,1-Jul-24\r\nDate,1-Jul-18,1-Jul-19,1-Jul-20,1-Jul-21,1-Jul-22,1-Jul-23,1-Jul-24\r\nDate,1-Jul-18,1-Jul-19,1-Jul-20,1-Jul-21,1-Jul-22,1-Jul-23,1-Jul-24\r\n

I need to remove the comma at the end of the first line (I think I need to be finding \r\n and killing any commas before that, until a non-comma.

Any thoughts about how to do this?

Thanks

Upvotes: 2

Views: 2247

Answers (3)

MarcoS
MarcoS

Reputation: 13564

I think you can match one or more , followed by \r\n by using ,+\\r\\n. Don't know how to replace that using C# sorry. In perl I would do

perl -pi -e 's/,+\\r\\n/\\r\\n/g' c.txt

(assuming that c.txt is a file containing your input text).

Upvotes: 0

Amber
Amber

Reputation: 526733

(,+$) perhaps? (One or more commas followed immediately by the end of a line.)

Upvotes: 6

Paul McLean
Paul McLean

Reputation: 3560

If your language supports positive lookahead, try this -

([,]*)(?=\\r\\n)

Upvotes: 1

Related Questions