tags:

views:

84

answers:

2

I need to remove all leading and trailing non-numeric characters. This is what I came up with. Is there a better implementation.

puts s.gsub(/^\D+/,'').gsub(/\D+$/,'')
+3  A: 

Perhaps a single #gsub(/(^\D+)|(\D+$)/, '')

Also, when in doubt Rubular it.

nowk
+1 for Rubular!
Mike Woodhouse
+5  A: 

Instead of eliminating what you don't want, it's often clearer to select what you do want (using parentheses). Also, this only requires one regex evaluation:

s.match(/^\D*(.*?)\D*$/)[1]

Or, this convenient shorthand:

s[/^\D*(.*?)\D*$/, 1]
Alex Reisner
Or possibly a simpler regular expression depending on what kind of strings you have.`"abc123def"[/\d+/] # => "123"`
Ben Marini