从字符串中提取Url

时间:2013-01-10 11:39:56

标签: ruby

我有一个网址:

url = "http://timesofindia.feedsportal.com/fy/8at2EuL0ihSIb3s7/story01.htmA"

最后有一些不需要的字符,如A,TRE。我想删除它,所以URL将是这样的:

url = http://timesofindia.feedsportal.com/fy/8at2EuL0ihSIb3s7/story01.htm

如何删除它们?

1 个答案:

答案 0 :(得分:2)

如果您的网址始终以.htm.apsx.php结束,您可以使用简单的正则表达式解决问题:

url = url[/^(.+\.(htm|aspx|php))(:?.*)$/, 1]

测试here at Rubular

首先,我使用this method来获取子字符串,就像切片一样。然后是正则表达式。从左到右:

^                   # Start of line
  (                   # Capture everything wanted enclosed
    .+                  # 1 or more of any character
    \.                  # With a dot after it
    (htm|aspx|php)      # htm or aspx or php
  )                   # Close url asked in question
  (                   # Capture undesirable part
    :?                  # Optional
    .*                  # 0 or more any character
  )                   # Close undesirable part
$                   # End of line