I am try to move a decimal point in RegEx. Example: 247.00 needs to be 2.470 (I had a typo, thanks Paul) The decimal point will always be need to be the second character.
I am spinning my wheels and I have no idea.
CodePudding user response:
You can replace matches of
(\d)(\d*)\.(\d )(?<!00)0*
with
$1.$2$3
For example, the string '247.200'
would become '2.4720'
. The negative lookbehind, (?<!00)
, prevents there being extra zeros at the end ('2.47200'
), consistent with your example.
If you want no trailing zeroes ('2.472'
), except when there is only one digit to the right of the decimal ('3.0'
), change the regex to:
(\d)(\d*)\.(\d )(?<![^.]0)0*
CodePudding user response:
Replace (\d)(\d*)\.(\d*)
with $1.$2$3
.
\d
matches a digit. The first regular expression matches a digit, followed by any number of digits, followed by a decimal point, and then followed by any number of additional digits. The capture groups capture each of those groups of digits, then back-references are used in the replacement string to insert the .
after the first digit.
In some languages the back-references are like \1
instead of $1
.