Coon
Coon

Reputation: 97

Regex for "replace all after first 2 digits after comma"

I would like to replace all characters after the first 2 digits after a comma.

E.g. having a string of 1234,56789 should result into 1234,56.

Using [^,]*$ has led me to the right path, but deleting everything after the comma.

A [^,]..$ doesnt give me a correct result too, thus I need a way to tell my expression that "the first 2 digits after the comma" got to be deleted, not "the last 2 digits" since thats what the ".." seems to do in my expression.

Upvotes: 2

Views: 1319

Answers (2)

roddar92
roddar92

Reputation: 366

You can use:

import re
re.sub(r',(\d{2}).*', r',\1', a)

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You can use

(,\d{2}).*

The regex matches and captures into Group 1 a comma and two digits, and just matches the rest of the line with .*.

To remove only after last comma:

(.*,\d{2}).*

Here, .* at the start captures also everything at the start of the string.

A more retrictive pattern will be

^(\d+,\d{2})\d*$

It matches start of string (with ^), then one or more digits (with \d+), a comma, two digits, all captured into Group 1, and then just matches zero or more digits (with \d*) at the end of the string ($).

Replace with $1 (or \1 depending on the regex engine). See the regex demo (also this one and this one, too).

Upvotes: 1

Related Questions