Coon
Coon

Reputation: 97

Regex replace keeping digits after comma AND the sign at the end of the number

I would like to replace all characters after the first 2 digits after a comma, as well as keep the negative sign at the end of the string.

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

Using (,\d{2}).* and replacing with "$1-" does indeed keep everything until 2 digits after comma, but it doesnt keep/add the minus sign at the end of the string.

I have tried (,\d{2}).*(-) and then replacing with "$1$2" too, but that didnt work neither.

Upvotes: 1

Views: 1362

Answers (2)

Max Xapi
Max Xapi

Reputation: 815

If you want to use a substitution, you can use (,\d{2})\d* and replace with $1

  • (,\d{2}): keeps the coma and the needed two digits
  • \d*: ignore the other digits

https://regex101.com/r/dcObRO/2

Upvotes: 2

Luis Colorado
Luis Colorado

Reputation: 12668

If you have a floating point number, it is better to make groups on it and rewrite the number as you desire, as in:

([0-9][0-9]*,[0-9][0-9])[0-9]*([-+])?
^ 1st group   two digits      ^ 2nd group (optional)

then you can convert it into

\1\2

as shown in this demo

Upvotes: 0

Related Questions