I have strings like this:
- "/detail/205193-foo-var-bar-foo.html"
- "/detail/183863-parse-foo.html"
- "/detail/1003-bar-foo-bar.html"
How to get ids (205193, 183863, 1003) from it with Ruby?
I have strings like this:
How to get ids (205193, 183863, 1003) from it with Ruby?
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+/] }
could also do something like this
"/detail/205193-foo-var-bar-foo.html".gsub(/\/detail\//,'').to_i
=> 205193
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
.
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
s = "/detail/205193-foo-var-bar-foo.html"
num = (s =~ /detail\/(\d+)-/) ? Integer($1) : nil