Skip to main content
added JavaScript and Python code; modified the original regular expression to skip empty matches
Source Link
manatwork
  • 32k
  • 8
  • 104
  • 93

If you definitely have to combine regular expressions and arithmetic operations, choose a language where the regular expression's replacement parameter can be a callback function. perl

Perl, Ruby, JavaScript and ruby would be the easiestPython are such languages:

bash-4.2$ echo 12 | perl -pe 's/[0-9]*\d+/$&+3/e'
15

bash-4.2$ echo 12 | ruby -pe '$_.sub!(/[0-9]*\d+/){|s|s.to_i+3}'
15

bash-4.2$ echo 12 | js -e 'print(readline().replace(/\d+/,function(s){return parseInt(s)+3}))'
15

bash-4.2$ echo 12 | python -c 'import re;print re.sub("\d+",lambda s:str(int(s.group(0))+3),raw_input())'
15

If you definitely have to combine regular expressions and arithmetic operations, choose a language where the regular expression's replacement parameter can be a callback function. perl and ruby would be the easiest:

bash-4.2$ echo 12 | perl -pe 's/[0-9]*/$&+3/e'
15

bash-4.2$ echo 12 | ruby -pe '$_.sub!(/[0-9]*/){|s|s.to_i+3}'
15

If you definitely have to combine regular expressions and arithmetic operations, choose a language where the regular expression's replacement parameter can be a callback function.

Perl, Ruby, JavaScript and Python are such languages:

bash-4.2$ echo 12 | perl -pe 's/\d+/$&+3/e'
15

bash-4.2$ echo 12 | ruby -pe '$_.sub!(/\d+/){|s|s.to_i+3}'
15

bash-4.2$ echo 12 | js -e 'print(readline().replace(/\d+/,function(s){return parseInt(s)+3}))'
15

bash-4.2$ echo 12 | python -c 'import re;print re.sub("\d+",lambda s:str(int(s.group(0))+3),raw_input())'
15
Source Link
manatwork
  • 32k
  • 8
  • 104
  • 93

If you definitely have to combine regular expressions and arithmetic operations, choose a language where the regular expression's replacement parameter can be a callback function. perl and ruby would be the easiest:

bash-4.2$ echo 12 | perl -pe 's/[0-9]*/$&+3/e'
15

bash-4.2$ echo 12 | ruby -pe '$_.sub!(/[0-9]*/){|s|s.to_i+3}'
15