在python中匹配字符串的开头和结尾与正则表达式

时间:2014-03-27 20:57:54

标签: python regex

我试图使用python从这个webpage中提取可解析引用信息。例如,对于列出的页面,我会拉pl / 111/148和pl / 111/152。我现在的正则表达式列在下面,但似乎在可解析引用后返回所有内容。它可能很简单,但我对正则表达式来说相对较新。提前谢谢。

re.findall(r'^parsable-cite=.*>$',page)

7 个答案:

答案 0 :(得分:2)

我强烈建议您使用此正则表达式来捕获您想要的内容:

re.findall(r'parsable-cite=\\\"(.*?)\\\"\>',page)

说明:

parsable-cite= matches the characters parsable-cite= literally (case sensitive)
  \\ matches the character \ literally
  \" matches the character " literally
  1st Capturing group (.*?)
  .*? matches any character (except newline)
      Quantifier: Between zero and unlimited times, as few times as possible,
           expanding as needed
  \\ matches the character \ literally
  \" matches the character " literally
  \> matches the character > literally

使用是关键;)

希望这会有所帮助。

答案 1 :(得分:1)

让你的正则表达式懒惰:

re.findall(r'^parsable-cite=.*?>$',page)
                              ^

或使用否定类(最好):

re.findall(r'^parsable-cite=[^>]*>$',page)
默认情况下,

.*会贪婪,并会在结束比赛前尝试尽可能匹配。

regex101 demo

如果您只想获得所需的部件,可以使用捕获组:

re.findall(r'^parsable-cite=([^>]*)>$',page)

regex101 demo


但是,从您的网页布局来看,您似乎不需要锚点(^$)(除非在网站上以某种方式移除换行符... )

答案 2 :(得分:1)

你所拥有的.*是“贪婪的”,这意味着它会尽可能多地匹配,包括任意数量的>个字符及其后的任何字符。

如果你真正想要的是“下一个>”的所有内容,那么你应该说[^>]*>,意思是“任意数量的非>字符,然后是{{ 1}}”。

答案 3 :(得分:1)

可能是这样的:

(?<=parsable-cite=\\\")\w{2}\/\d{3}\/\d{3}

http://regex101.com/r/kE9uE3

答案 4 :(得分:1)

虽然这是一个json字符串,其中嵌入了html,但您仍然可以使用BeautifulSoup来实现此目的:

soup = BeautifulSoup(htmls);
tags = soup.findAll("external-xref", {"parsable-cite":re.compile("")})
for t in tags:
    print t['parsable-cite']

答案 5 :(得分:1)

如果它位于\"分隔符

之间,则可能会有效
 #  \bparsable-cite\s*=\s*\"((?s:(?!\").)*)\"

 \b 
 parsable-cite
 \s* = \s* 
 \"
 (                             # (1 start)
      (?s:
           (?! \" )
           . 
      )*
 )                             # (1 end)
 \"

或者,只是

 #  (?s)\bparsable-cite\s*=\s*\"(.*?)\"

 (?s)
 \b 
 parsable-cite
 \s* = \s* 
 \"
 ( .*? )                 # (1)
 \"

答案 6 :(得分:1)

如果您认为每次都非常相似:

re.findall(r"pl/\d+/\d+", page)
相关问题