【问题标题】:Finding substrings enclosed within first brackets查找包含在第一个括号内的子字符串
【发布时间】:2021-09-29 10:17:41
【问题描述】:

我有一个字符串如下:

" I wanted my friends (he), (she), (they) around"

我想获得一个包含["he", "she", "they"] 的列表。

以下是我的代码:

copy = " (he), (she), (they)"
x = re.findall(r'^{.}$', copy)

但这给了我一个空列表作为输出。

我还尝试了以下方法:

import re

copy = '{he},{she}, {they}'
x = re.findall(r'\{([^]]*)\}', copy)
print(x)

但在这种情况下,输出是:

['he},{she}, {they']

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    您可以使用\((\w+)\)(括号括起来的任何连续的单词字符):

    import re
    re.findall('\((\w+)\)', your_string)
    

    输入:your_string = " I wanted my friends (he), (she), (they) around"

    输出:['he', 'she', 'they']

    【讨论】:

      【解决方案2】:

      首先,您的示例中有圆括号(),而不是大括号{},其次^ 表示行或字符串的开头(取决于模式),而括号中的表达式在里面,第三是@ 987654327@ 表示行尾或字符串(取决于模式),而括号内的表达式在里面。你应该这样做

      import re
      text =  " I wanted my friends (he), (she), (they) around"
      print(re.findall(r'\((.+?)\)',text))
      

      输出

      ['he', 'she', 'they']
      

      请注意,我使用了所谓的原始字符串以避免过度转义(请参阅re module docs 以进行进一步讨论)并且需要使用\(\) 来表示文字(和文字),否则(和) 表示组,也用于上述模式。 .+? 表示非贪婪匹配任意字符中的一个或多个,? 对于避免单一匹配 he), (she), (they 很重要。

      【讨论】:

        【解决方案3】:

        试试这个:try it online

        >>> copy = " I wanted my friends (he), (she), (they) around"
        >>> re.findall(r'\((.*?)\)', copy)
        ['he', 'she', 'they']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-11-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-01
          • 1970-01-01
          相关资源
          最近更新 更多