【问题标题】:How to split a string with parentheses and spaces into a list如何将带括号和空格的字符串拆分为列表
【发布时间】:2022-01-13 21:05:12
【问题描述】:

我想拆分如下字符串:

(so) what (are you trying to say)
 
what (do you mean)

进入如下列表:

[(so), what, (are you trying to say)]

[what, (do you mean)]

我尝试过的代码如下。在站点 regexr 中,正则表达式匹配我想要的部分但给出警告,所以......我不是正则表达式专家,我不知道我做错了什么。

import re
string = "(so) what (are you trying to say)?"

rx = re.compile(r"((\([\w \w]*\)|[\w]*))")

print(re.split(rx, string ))

【问题讨论】:

    标签: python regex


    【解决方案1】:

    使用[\w \w]*[\w ]* 相同,也匹配一个空字符串。

    您可以使用 re.findall 而不使用任何捕获组,而不是使用拆分,并编写如下模式:

    \(\w+(?:[^\S\n]+\w+)*\)|\w+
    
    • \(匹配(
      • \w+ 匹配 1+ 个单词字符
      • (?:[^\S\n]+\w+)* 可选择重复匹配空格和 1+ 个单词字符
    • \) 匹配)
    • |或者
    • \w+匹配1+字字符

    Regex demo

    import re
    string = "(so) what (are you trying to say)? what (do you mean)"
    
    rx = re.compile(r"\(\w+(?:[^\S\n]+\w+)*\)|\w+")
    
    print(re.findall(rx, string))
    

    输出

    ['(so)', 'what', '(are you trying to say)', 'what', '(do you mean)']
    

    【讨论】:

      【解决方案2】:

      对于你的两个例子,你可以写:

      re.split(r'(?<=\)) +| +(?=\()', str)
      

      Python regex¯\(ツ)>Python code

      但是,这对于 OP 代码中定义的 string 不起作用,其中包含一个问号,这与两个示例中的问题陈述相反。

      正则表达式可以分解如下。

      (?<=\)) # positive lookbehind asserts that location in the
              # string is preceded by ')'
      [ ]+    # match one or more spaces
      |       # or
      [ ]+    # match one or more spaces
      (?=\()  # positive lookahead asserts that location in the
              # string is followed by '('
      

      在上面我将两个空格字符中的每一个都放在一个字符类中只是为了让它可见。

      【讨论】:

        猜你喜欢
        • 2021-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-12
        • 1970-01-01
        • 2020-09-20
        相关资源
        最近更新 更多