2016-03-04 42 views
1

我想匹配在以下链接类别:newspolitics使用python正则表达式匹配URL中的类别?

注意,可能有1个或多个类别。可以通过在文本或/之间使用/来识别类别。

我的尝试:

item.url = 'http://www.example.com/news/politics/this-is-article-name-1993591' 

compiled_regex = re.compile('/.+(?!/)/') 

match = compiled_regex.search(item.url) 

响应None

我想什么(预期结果):

match.group(0) = `news` 
match.group(1) = `politics` 
+0

什么是预期的输出 ?有没有你想要的图案?请稍微清楚一点。 – 2016-03-04 13:47:54

回答

1

按照自己的定义,这样的事情:

categories = item.url.split('/')[3:-1] 
3

,而不是一个正则表达式,我会使用urllib.parse它是由然而解析除其他事项外

>>> url = 'http://www.example.com/news/politics/this-is-article-name-1993591' 
>>> import urllib.parse 

>>> urllib.parse.urlparse(url) 
ParseResult(scheme='http', 
      netloc='www.example.com', 
      path='/news/politics/this-is-article-name-1993591', 
      params='', 
      query='', 
      fragment='') 

>>> urllib.parse.urlparse(url).path 
'/news/politics/this-is-article-name-1993591' 

>>> urllib.parse.urlparse(url).path.split('/')[1:-1] 
['news', 'politics'] 
1

其他证明有用的答案的网址,如果你真的真的需要使用正则表达式:

>>> import re 
>>> url = 'http://www.example.com/news/politics/this-is-article-name-1993591' 
>>> re.match('https?://[^/]+/([^/]+)/([^/]+)/', url).groups() 
('news', 'politics') 
+1

我测试了这种情况,并且只有2个类别在url中才会起作用,1和3或更多不起作用 – surfer190

+0

是的,这意味着必须有(至少)两个“类别”。网址结构取决于网站,根据您尝试解析的网站,您可能必须拥有多种不同的策略。如果你认为一个正则表达式可以匹配它们,你可能会以错误的方式接近问题。 – hruske