Home > Software engineering >  Remove "." from digits
Remove "." from digits

Time:02-22

I have a string in the following way =

"lmn abc 4.0mg  3.50 mg over 12 days. Standing nebs."

I want to convert it into :

"lmn abc 40mg  350 mg over 12 days. Standing nebs."

that is I only convert a.b -> ab where a and b are integer waiting for help

CodePudding user response:

Assuming you are using Python. You can use captured groups in regex. Either numbered captured group or named captured group. Then use the groups in the replacement while leaving out the ..

import re
text = "lmn abc 4.0mg  3.50 mg over 12 days. Standing nebs."

Numbered: You reference the pattern group (content in brackets) by their index.

text = re.sub("(\d )\.(\d )", "\\1\\2", text)

Named: You reference the pattern group by a name you specified.

text = re.sub("(?P<before>\d )\.(?P<after>\d )", "\g<before>\g<after>", text)

Which each returns:

print(text)
> lmn abc 40mg  350 mg over 12 days. Standing nebs.

However you should be aware that leaving out the . in decimal numbers will change their value. So you should be careful with whatever you are doing with these numbers afterwards.

CodePudding user response:

Using any sed in any shell on every Unix box:

$ sed 's/\([0-9]\)\.\([0-9]\)/\1\2/g' file
"lmn abc 40mg  350 mg over 12 days. Standing nebs."
  • Related