Remove numbers from string array

I have an array that looks like this:

["lorem", "ipsum", "1734", "dolor", "1", "301", "et", "4102", "92"] 

Is there a way to remove all numbers in an array, even if they are stored as strings, so I would stay with this:

 ["lorem", "ipsum", "dolor", "et"] 

Thanks for any tips.

+4
source share
4 answers

Use regex pattern

 s = ["lorem", "ipsum", "1734", "dolor", "1", "301", "et", "4102", "92"] s.reject { |l| l =~ /\A\d+\z/ } # => ["lorem", "ipsum", "dolor", "et"] 
+5
source
 s = ["lorem", "ipsum", "1734", "dolor", "1", "301", "et", "4102", "92"] s.reject{|s| s.match(/^\d+$/) } 
+4
source

If all your lines are integers, @Simone's answer will work well.

If you need to check all the numerical representations (floats and scientific notation), you can:

 s = %w[ foo 134 0.2 3e-3 bar ] s.reject!{ |str| Float(str) rescue false } ps #=> ["foo", "bar"] 
+2
source

One thing can be said: REGEX compliance

  • Loop though all the elements
  • Then use this:

     txt='Your string' re1='(\\d+)' # Integer Number 1 re=(re1) m=Regexp.new(re,Regexp::IGNORECASE); if m.match(txt) int1=m.match(txt)[1]; # REMOVE THE ITEM HERE end 
0
source

Source: https://habr.com/ru/post/1440605/


All Articles