Reputation: 71
I have a string:
10 101/12/201209/12/2012 8 75.00 600.00 2 1RPT/136185RAMADA HOTEL & SUITES
I want to get from this value from the string:
136185
I tried to use /([^\/]*)$/
, but it returned:
136185RAMADA HOTEL
What should I do?
Upvotes: 0
Views: 491
Reputation: 111
The inverse of using scan
is to use split
:
s = '10 101/12/201209/12/2012 8 75.00 600.00 2 1RPT/136185RAMADA HOTEL & SUITES'
s.split(/\D+/).last # Everything that isn't a number is a separator, take the last one
=> "136185"
If the rule is first number after the last '/', then this works even if the business has digits in its name:
s = '10 101/12/201209/12/2012 8 75.00 600.00 2 1RPT/136185MOTEL 6'
s.split(?/).last.to_i # => 136185
Note that "7 Seas Hotel" is going to still cause problems
Upvotes: 1
Reputation: 1208
I don't know if it's the shortest solution but (\d+)\D*\Z
should work.
Upvotes: 1
Reputation: 160549
If the number is ALWAYS six digits, use:
'10 101/12/201209/12/2012 8 75.00 600.00 2 1RPT/136185RAMADA HOTEL & SUITES'.split[6].split('/').last[0, 6]
=> "136185"
The potential problem with any regex solution is the number + hotel name could cause solutions using \d+
to return bad values if the hotel's name is something like 7 Seas
.
Upvotes: 0
Reputation: 168101
str = "10 101/12/201209/12/2012 8 75.00 600.00 2 1RPT/136185RAMADA HOTEL & SUITES"
str[/\d+(?=\D*\z)/]
# => "136185"
Upvotes: 1
Reputation: 27793
Try
string[/.*\b(\d+)/,1]
this matches as many characters as possible before matching a group of digits, starting with a word boundary to make sure the greedy .*
doesn't eat up the begin of the digit group.
Or use
string.scan(/\d+/).last
which is more readable, but not a pure regex.
Upvotes: 0