【问题标题】:Find string between two patterns with an AND condition in Python在 Python 中使用 AND 条件查找两个模式之间的字符串
【发布时间】:2019-08-09 13:43:19
【问题描述】:

我想识别介于两个模式之间的字符串(例如lettre/ 和 ")。此外,识别的字符串不应对应于第三个模式(例如somth?other)。

在 MAC OSX 10.13 上运行的 Python 3.7

import re
strings = ['lettre/abc"','lettre/somth?other"','lettre/acc"','lettre/edf"de','lettre/nhy"','lettre/somth?other"']

res0_1 = re.search('lettre/.*?\"', strings[0])
res1_1 = re.search('lettre/.*?\"', strings[1])
print(res0_1)
<re.Match object; span=(0, 11), match='lettre/abc"'>
print(res1_1)
<re.Match object; span=(0, 19), match='lettre/somth?other"'>

res0_2 = re.search('lettre/(.*?\"&^[somth\?other])', strings[0])
res1_2 = re.search('lettre/(.*?\"&^[somth\?other])', strings[1])
print(res0_2)
None
print(res1_2)
None

我想为strings[0] 获取res0_1,为strings[1] 获取res1_2

【问题讨论】:

标签: python regex python-3.x search


【解决方案1】:

据我了解 试试这个:

import re
strings = ['lettre/abc"','lettre/somth?other"','lettre/acc"','lettre/edf"de','lettre/nhy"','lettre/somth?other"']

res0_1 = re.findall('lettre/(.*)\"', strings[0])
res1_2 = re.findall('lettre/(.*)\"', strings[1])
print(res0_1)
print(res1_2)

希望对你有帮助

【讨论】:

    【解决方案2】:

    我认为下面的代码可以为您提供您在问题中提出的问题。

    import re
    strings = ['lettre/abc"','lettre/somth?other"','lettre/acc"','lettre/edf"de','lettre/nhy"','lettre/somth?other"']
    
    for i in strings:
        if 'somth?other' not in i.split('/')[1]:
            print(i.split('/')[1].split('"')[0])
    

    【讨论】:

      【解决方案3】:

      如果somth?other/ 的右侧,你不想匹配,你可以使用

      r'lettre/(?!somth\?other)[^"]*"'
      

      查看regex demo 和正则表达式图:

      详情

      • lettre/ - 文字子串
      • (?!somth\?other) - 当前位置右侧不允许有 somth?other 子字符串
      • [^"]* - 除了" 之外的 0+ 个字符
      • " - 双引号。

      【讨论】:

        【解决方案4】:

        尝试使用此网站,而不是尝试和错误。 https://regex101.com/

        In [7]: import re 
           ...: strings = ['lettre/abc"','lettre/somth?other"','lett
           ...: re/acc"','lettre/edf"de','lettre/nhy"','lettre/somth
           ...: ?other"'] 
           ...:                                                     
        
        In [8]: c = re.compile('(?=lettre/.*?\")(^((?!.*somth\?other
           ...: .*).)*$)')                                          
        
        In [9]: for string in strings: 
           ...:     print(c.match(string)) 
           ...:                                                     
        <re.Match object; span=(0, 11), match='lettre/abc"'>
        None
        <re.Match object; span=(0, 11), match='lettre/acc"'>
        <re.Match object; span=(0, 13), match='lettre/edf"de'>
        <re.Match object; span=(0, 11), match='lettre/nhy"'>
        None
        

        【讨论】:

          猜你喜欢
          • 2016-11-20
          • 2019-05-19
          • 1970-01-01
          • 2017-07-07
          • 2015-02-05
          • 1970-01-01
          • 1970-01-01
          • 2012-05-19
          • 1970-01-01
          相关资源
          最近更新 更多