2

I want to get the numbers out of strings such as:

person_3
person_34
person_356
city_4
city_15

etc...

It seems to me that the following should work:

string[/[0-9]*/]

but this always spits out an empty string.

2
  • string[/_.*$/][1..-1] works, but I'm still curious why just asking for the [0-9]* doesn't work... Commented Aug 18, 2010 at 18:33
  • ruby -v ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-linux] Commented Aug 18, 2010 at 18:35

1 Answer 1

9

[0-9]* successfully matches "0 or more" digits at the beginning of the string, so it returns "". [0-9]+ will match "1 or more" digits, and works as you expect:

irb(main):001:0> x = "test 92"
=> "test 92"
irb(main):003:0> x[/\d*/]
=> ""
irb(main):005:0> x.index(/\d*/)
=> 0
irb(main):004:0> x[/\d+/]
=> "92"
Sign up to request clarification or add additional context in comments.

2 Comments

It's not because of non-greedy matching (which it isn't), but because * matches zero or more chars. It finds zero digits in the beginning of the string, and returns them. You can test this by trying the same regex on string "34_person", /[0-9]*/ will return both digits.
Its not being greedy, its being lazy! Thanks to both.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.