fairy hunter fairy hunter - 7 months ago 14
Java Question

How to remove the two digit or one digit after the comma and the remaining character after that? -Regex

I have some list of numbers:

1,000,000,00

1,000,000,0

1,000,000,000

1,00,0000,000


The expected output:

1,000,000

1,000,000

1,000,000,000

1

So, when there are only two digits and one digit after the last comma, the digit won't get
saved by the program and it just left out. So, how am i supposed to do with this problem
when I want to saved the input?


For example of what I am currently thinking:


textField1.getText().{someCodeToRemoveTwoOrOneDigit}

Answer

If all you want to do is remove a trailing 1- or 2-digit block, then do this:

text.replaceAll(",\\d{1,2}$", "")
1,000,000,00   ->  1,000,000
1,000,000,0    ->  1,000,000
1,000,000,000  ->  1,000,000,000
1,00,000,000   ->  1,00,000,000
$1,00,000,000  ->  $1,00,000,000

If you want to only retain a "valid" number, i.e. a number with 1-3 leading digits, following by X number of 3-digit blocks, then do this:

text.replaceAll("\\D*(\\d{1,3}(?:,\\d{3})*)?.*", "$1")
1,000,000,00   ->  1,000,000
1,000,000,0    ->  1,000,000
1,000,000,000  ->  1,000,000,000
1,00,000,000   ->  1
$1,00,000,000  ->  1