Maciek
Maciek

Reputation: 1992

Regex match all non-digits except decimal or comma at a specific position

Here are my numbers:

$1,000,000.00
100000000.00
100000
$1,000.00
2.000,00
10000,00

I would like to get:

1000000.00
100000000.00
100000
1000.00
2000,00
10000,00

Here is my regex:

[^\d(,.{3})]

I would like to remove all non-digits except a decimal or comma if it's in the 3rd position from the right. Is this possible?

Upvotes: 0

Views: 1394

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370999

Character sets (or negative character sets) should only contain those characters that you want to match, or those you don't want to match - if you want to carry out additional tests (such as the character in question not being near the end of the line), do those tests outside of the character set.

Here, you can use the negative character set

[^\d\n,.]

to match characters that aren't digits, newlines, commas, or periods, and alternate that character set with

[,.](?!\d{2}$)

which will match periods and commas that aren't followed by two digits and the end of the line. In full:

[^\d\n,.]|[,.](?!\d{2}$)

and replace with the empty string. Output:

1000000.00
100000000.00
100000
1000.00
2000,00
10000,00

https://regex101.com/r/y0s1Bw/1

Upvotes: 4

Related Questions