Regex multiplication

前端 未结 2 1400
情话喂你
情话喂你 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.

    0 讨论(0)
  • 2021-01-25 06:59

    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.

    0 讨论(0)
提交回复
热议问题