Reputation: 8111
I have strings like this:
How to get ids (205193, 183863, 1003) from it with Ruby?
Upvotes: 0
Views: 1636
Reputation: 144206
s = "/detail/205193-foo-var-bar-foo.html"
num = (s =~ /detail\/(\d+)-/) ? Integer($1) : nil
Upvotes: 0
Reputation: 146231
s[/\d+/]
[
"/detail/205193-foo-var-bar-foo.html",
"/detail/183863-parse-foo.html",
"/detail/1003-bar-foo-bar.html"
].each { |s| puts s[/\d+/] }
Upvotes: 4
Reputation: 15506
One easy way to do it would be to strip out the /detail/
part of your string, and then just call to_i
on what's left over:
"/detail/1003-bar-foo-bar.html".gsub('/detail/','').to_i # => 1003
Upvotes: 1
Reputation: 20232
could also do something like this
"/detail/205193-foo-var-bar-foo.html".gsub(/\/detail\//,'').to_i
=> 205193
Upvotes: 3
Reputation: 12574
regex = /\/detail\/(\d+)-/
s = "/detail/205193-foo-var-bar-foo.html"
id = regex.match s # => <MatchData "/detail/205193-" 1:"205193">
id[1] # => "205193"
$1 # => "205193"
The MatchData
object will store the entire matched portion of the string in the first element, and any matched subgroups starting from the second element (depending on how many matched subgroups there are)
Also, Ruby provides a shortcut to the most recent matched subgroup with $1
.
Upvotes: 1