0

Am trying to allow and print only numeric characters. To this effect, I have reference solution found here which uses str.gsub("/some regex/", '') method but cannot get it to work. source here is the code

 mystring= 'Food1248is read 100'
    result = mystring.gsub("[^0-9]", '')

    print(result)

I need to only get the numbers from the string variable above

Nancy Moore
  • 2,322
  • 2
  • 21
  • 38

4 Answers4

0
mystring= 'Food1248is read 100'    
mystring.gsub(/\D/, '')
=> "1248100"
Umesh Malhotra
  • 967
  • 1
  • 10
  • 25
  • Thanks Umesh. I never guess that. The regex [^0-9] works very well with my python flask and Django apps. you saved my time. – Nancy Moore Apr 15 '19 at 12:10
0
mystring= 'Food1248is read 100'
p mystring.scan(/\d+/).join

output

"1248100"
Rajagopalan
  • 5,465
  • 2
  • 11
  • 29
0
mystring= 'Food1248is read 100'
mystring.gsub(/[a-zA-Z]/, '').delete(' ')

Output:

1248100
0

In str.gsub("/some regex/", '') "/some regex/" is not a regex, it is a string. /some regex/ is a regex; just as /[^0-9]/ which would work.

steenslag
  • 79,051
  • 16
  • 138
  • 171