views:

43

answers:

1

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.

+3  A: 

[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"
meagar
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.
Mladen Jablanović
@Mladen Ahh, of course. Thank you.
meagar
Its not being greedy, its being lazy! Thanks to both.
muirbot
string[/[0-9]*$/] also works.
muirbot