【问题标题】:re.search() logically or two patterns in re.search()re.search() 逻辑上或 re.search() 中的两个模式
【发布时间】:2015-04-09 21:12:49
【问题描述】:

我有以下字符串。

Page load for http://xxxx?roxy=www.yahoo.com&sendto=https://mywebsite?ent took 4001 ms (Ne: 167 ms, Se: 2509 ms, Xe: 1325 ms)<br><br><br>Topic: Yahoo!! My website is a good website | Mywebsite<br>

Page load for http://xxxx?roxy=www.yahoo.com&sendto=https://mywebsite?ent took too long (12343 ms Ne: 167 ms, Se: 2509 ms, Xe: 1325 ms)<br><br><br>Topic: Yahoo!! My website is a good website | Mywebsite<br>

我想从ent took 4001 ms OR 中提取上面的4001 OR 12343 OR ent took too long (12343 ms 并将其分配给变量

tt = int(re.search(r"\?ent\s*took\s*(\d+)",message).group(1))

这个正则表达式确实匹配第一部分并返回 4001。我如何在逻辑上或表达式 r"\?ent\s*\took\s*too\s*long\s*\((\d+)" 从第二部分提取12343?

【问题讨论】:

  • 你看/usr/lib64/python2.7/re.py的第242行了吗?

标签: python regex findall


【解决方案1】:

正则表达式开头的问号不跟随任何可以设为可选的内容。如果你想在那里匹配一个文字问号,写\?

x = int(re.findall(r"\?ent\s*took\s*([^m]*)",message)[0])

【讨论】:

    【解决方案2】:

    这一次匹配两种模式并提取所需的数字:

    tt = int(re.search(r"\?ent took (too long \()?(?P<num>\d+)",message).group('num'))
    

    【讨论】:

      【解决方案3】:

      首先,您需要在模式的开头转义?,因为? 标记是一个正则表达式字符,并且使字符串可选并且必须以字符串开头!所以如果你想计算?,你需要使用\?作为一种更有效的方式,你可以在你的模式中使用re.search\d+,并拒绝额外的索引:

      >>> int(re.search(r"\?ent\s*took\s*(\d+)",s).group(1))
      4001
      

      对于第二个例子,你可以这样做:

      >>> re.search(r'\((\d+)',s).group(1)
      '12343'
      

      对于这两种情况的匹配,请使用以下模式:

      (\d+)[\s\w]+\(|\((\d+)
      

      Demo

      >>> s1="Page load for http://xxxx?roxy=www.yahoo.com&sendto=https://mywebsite?ent took too long (12343 ms Ne: 167 ms, Se: 2509 ms, Xe: 1325 ms)<br><br><br>Topic: Yahoo!! My website is a good website | Mywebsite<br>"
      >>> s2="Page load for http://xxxx?roxy=www.yahoo.com&sendto=https://mywebsite?ent took 4001 ms (Ne: 167 ms, Se: 2509 ms, Xe: 1325 ms)<br><br><br>Topic: Yahoo!! My website is a good website | Mywebsite<br>"
      >>> re.search(r'(\d+)[\s\w]+\(|\((\d+)',s1).group(2)
      '12343'
      >>> re.search(r'(\d+)[\s\w]+\(|\((\d+)',s2).group(1)
      '4001'
      

      【讨论】:

      • 他大概想匹配在 URL 中标记查询字符串开头的文字 ?
      • @liv2hak 你可以使用r'\((\d+)'检查编辑!
      • @Kasra - 我不知道我会提前收到哪一条消息。我需要一个匹配两者的模式。
      • @Kasra - 如果我使用 ` tt = int(re.search(r"(\d+)[\s\w]+(|((\d+)",message.group(1 )))` 我得到AttributeError: 'unicode' object has no attribute 'group'
      • @liv2hak 但它对我来说很好,因为我在回答中添加了!你确定你已经正确运行了吗?
      猜你喜欢
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      相关资源
      最近更新 更多