3

i am wondering of it is possible to do some simple Math on RegEx Variable values. E.G.:

I am looking for all two-digit numbers is a textfile and would like to multiply them by 10. Is simple regex able to do this or do i need to use a more complex script for that?

thanks!

zantafio
  • 737
  • 1
  • 8
  • 25

1 Answers1

3

Multiply two-digits number is like appending 0 at the end of the numbers. So that can be done with any regular expression that support replace and capturing group.

For example, here is Python code:

>>> re.sub(r'\b(\d{2})\b', r'\g<1>0', 'There are 10 apples.')
'There are 100 apples.'

But what you want is multiply by arbitrary number, then you need the regular expression engine that support some kind of callback / evaluation.

>>> re.sub(r'\b(\d{2})\b', lambda m: str(int(m.group(1)) * 5), '10 apples.')
'50 apples.'
falsetru
  • 357,413
  • 63
  • 732
  • 636