Regex multiplication

前端 未结 2 1399
情话喂你
情话喂你 2021-01-25 05:54

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 v

2条回答
  •  再見小時候
    2021-01-25 06:34

    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.

提交回复
热议问题