fork(1) download
  1. # To support positive/negative integer/float numbers, you could use a slightly modified regexp from http://stackoverflow.com/questions/385558/python-and-regex-question-extract-float-double-value:
  2.  
  3. import sys
  4. def main():
  5. import re
  6.  
  7. re_float = re.compile("""(?x)
  8. ^
  9. [+-]?\ * # first, match an optional sign *and space*
  10. ( # then match integers or f.p. mantissas:
  11. \d+ # start out with a ...
  12. (
  13. \.\d* # mantissa of the form a.b or a.
  14. )? # ? takes care of integers of the form a
  15. |\.\d+ # mantissa of the form .b
  16. )
  17. ([eE][+-]?\d+)? # finally, optionally match an exponent
  18. """)
  19.  
  20. def extract_number(s, default=None):
  21. m = re_float.match(s)
  22. if not m:
  23. return default # no number found
  24. f = float(m.group(0))
  25. return int(f) if f.is_integer() else f
  26.  
  27. ### Example
  28.  
  29. for s in sys.stdin:
  30. print(extract_number(s, default=0))
  31.  
  32. main()
  33.  
Success #stdin #stdout 0.01s 7732KB
stdin
1234alpha
a1234asdf
1234.56yt
-1e20.
12.34.56
stdout
1234
0
1234.56
-100000000000000000000
12.34