【问题标题】:How to extract strings from nested symbols? [duplicate]如何从嵌套符号中提取字符串? [复制]
【发布时间】:2021-08-24 14:33:14
【问题描述】:

对不起,我不知道如何命名这个线程。

我需要从string 中提取()"" 的第一层,但是当我尝试使用re 时,它只会返回第一层和第二层() 之间的所有内容。

import re

string = 'this is a test ("string with (some) paranthesis") how great'
extract = re.findall('\((.*?)\)', string)

print(extract)

输出:

['"string with (some']

但我需要:

['"string with (some) paranthesis"']

或者没有""

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    使用贪婪的量词而不是懒惰的量词:

    extract = re.findall('\((.*)\)', string)
    

    【讨论】:

      【解决方案2】:

      删除?:

      import re
      
      string = 'this is a test ("string with (some) paranthesis") how great'
      extract = re.findall(r'\((.*)\)', string)
      
      print(extract)
      

      ? 不是多余的,因为您已经有 .* 来匹配括号之间的所有内容;它使匹配不贪婪,这意味着.* 将匹配以括号结尾的最短字符序列,即("string with (some)

      【讨论】:

      • 这很容易。谢谢。将在几分钟内奖励。
      • ? 在这里不是多余的,是错误的。
      【解决方案3】:

      根据您需要的具体程度,您可以尝试以下方法:

      import re
      
      string = 'this is a test ("string with (some) paranthesis") how great'
      extract = re.findall(r'\((".*?")\)', string)
      

      如果字符串中有后续括号,则模式'\((.*)\)' 将无法正常工作,例如

      string = 'this is a test ("string with (some) paranthesis") how (really) great'
      

      那么,根据您的字符串,r'\((".*?")\)' 可能也不合适。

      【讨论】:

        【解决方案4】:

        也许一个简单的拆分就足以满足您的需求:

        string  = 'this is a test ("string with (some) paranthesis") how great'
        
        extract = string.split("(",1)[-1].rsplit(")",1)[0]
        
        print(extract)
        # "string with (some) paranthesis"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-07-27
          • 2022-12-23
          • 2022-10-12
          • 1970-01-01
          • 1970-01-01
          • 2021-03-06
          • 2019-10-15
          • 1970-01-01
          相关资源
          最近更新 更多