Friday, April 29, 2011

Get the number between specified strings

Ok. Given the example of:

http://example.com/news/3226-some-post-title.html

I'm trying to get the 3226. This regexp: http:\/\/interaktywnie.com\/newsy\/(.*).html doesn't seem to work. Please help.

Thanks.

From stackoverflow
  • You can just use:

       /\/(\d+)-(.*)\.html$/
    

    This will grab the digits (\d) after the '/' and put the digits into the first variable once it finds them.

    A great place to test regular expression is http://rubular.com/.

    Chas. Owens : you need to escape that last .
    vrish88 : ah thanks. good eye.
  • You want this:

    /http:\/\/example.com\/news\/(\d+)-.+\.html/
    

    \d is any digit. Also, the following site is very useful for regular expressions in ruby:

    http://www.rubular.com

  • Try this pattern:

    /http:\/\/example\.com\/news\/(\d+)-.+\.html/
    

    So:

    match = /http:\/\/example\.com\/news\/(\d+)-.+\.html/.match("http://example.com/news/3226-some-post-title.html")
    puts match[1]
    
  • "http://example.com/news/3226-some-post-title.html".split("/").last.to_i
    

0 comments:

Post a Comment