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!

1
  • Really a bad idea to do math on regex Commented Nov 11, 2013 at 13:28

1 Answer 1

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.'
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, of course the latter is what i wanted, multiply by 10 was just an example ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.