Regex multiplication

萝らか妹 提交于 2020-07-16 06:00:08

问题


looked around for a while before I asked but I seem to find a lot of how to's on email and currency conversion using regex but nothing on just multiplying a number with a set value. Essentially, I have a currency value field of lets say: 127.25GBP which needs to be converted to 165.42 (only two decimal points and no currency indicator) Can that be done and if yes how?

Your help would be greatly appreciated!

Thanx

Del


回答1:


Regular expressions are intended for text-matching, not arithmetics. Some of the tools that accept regexes can be used to perform arithmetics, like Perl and Awk for instance.




回答2:


Regexes, at their core, are intended for matching strings, and in some software libraries for replacing strings with others and similar string processing, but not for doing math. You need to store the value you capture using a regex into a numerical type and do the multiplication on that, then format the result as a string again if needed.

In python 2.7:

import re
exchangeRate = 165.42 / 127.25
numString = re.match('(\d+.\d\d)GBP', '127.25GBP').group(1)
num = float(numString)
numConverted = num * exchangeRate
numConvertedFormatted = "%.2f" % numConverted

If you're doing serious currency calculations, I'd advise for using fixed-point int (or in case of Python decimal) instead of float, though. For approximations float is good enough.



来源:https://stackoverflow.com/questions/5002981/regex-multiplication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!