TTaJTa4
TTaJTa4

Reputation: 840

regex to remove everything after the last comma in a string

I would like to write a regex in Perl which will remove everything after the last comma in a string. I know the substring after the last comma is a number or some other substring, so no commas there.

Example: some\string,/doesnt-really.metter,5.

I would like the regex to remove the last comma and the 5 so the output would be: some\string,/doesnt-really.metter

I am not allowed to use any additional module only with regex. So which regex should I use?

Another example:

string_with,,,,,_no_point,some_string => string_with,,,,,_no_point

Upvotes: 0

Views: 9340

Answers (3)

sandeep singh
sandeep singh

Reputation: 47

perl -n -e 'chomp; s/(.+,)/$1/g; print "$_\n";' inputfile.txt

Just run this command directly on terminal, the regex just selects all text which comes before last comma).

Upvotes: -1

Laurent Mouchart
Laurent Mouchart

Reputation: 216

This Regex captures everything before the last ,.

(.*),[^,]*$

Upvotes: 0

Dave Mitchell
Dave Mitchell

Reputation: 2403

If the comma is always followed by one or more digits, you can use: s/,\d+$//. More generally, use s/,[^,]*$// (match a comma followed by zero or more non-comma characters followed by end-of-string).

Upvotes: 7

Related Questions