0

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?

Kir
  • 7,981
  • 12
  • 52
  • 69
  • possible dups: http://stackoverflow.com/questions/899953/whats-the-ruby-way-to-parse-a-string-for-a-single-key-value http://stackoverflow.com/questions/1208137/parsing-string-in-ruby – 08Hawkeye Dec 10 '10 at 19:56

5 Answers5

4

Just say 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+/] }
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
3

could also do something like this

"/detail/205193-foo-var-bar-foo.html".gsub(/\/detail\//,'').to_i
 => 205193
Doon
  • 19,719
  • 3
  • 40
  • 44
1
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 .

bowsersenior
  • 12,524
  • 2
  • 46
  • 52
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

girasquid
  • 15,121
  • 2
  • 48
  • 58
0
s = "/detail/205193-foo-var-bar-foo.html"
num = (s =~ /detail\/(\d+)-/) ? Integer($1) : nil
Lee
  • 142,018
  • 20
  • 234
  • 287
  • 1
    -:2: invalid regular expression; there's no previous pattern, to which '+' would define cardinality at 10: /detail\/(+d)-/ – Kir Dec 10 '10 at 20:34