【问题标题】:Regex Lookahead and lookbehind multiple times in Python正则表达式在 Python 中多次前瞻和后瞻
【发布时间】:2019-10-24 04:43:09
【问题描述】:

我的输入格式如下(txt1):

txt1 = "[('1','Hello is 1)people 2)animals'), ('People are 1) hello 2) animals'), ('a')]"

我想把它提取成以下格式-

[['1','Hello is 1)people 2)animals'],['People are 1) hello 2) animals'],['a']]

所以,基本上,我想要括号内的信息。但我无法做到这一点。此外,我使用了 Lookahead 和 Lookbehind 来避免被数字拆分 - '1)' 或 '2)' 之前我在re.split('[\(\)\[\]] 的简单语句中发生了这种情况

我一直在尝试使用 findall 功能来检查我得到了什么。

r = re.findall(r'\((?=\').*(?<=\')\)(?=\,)', txt1)

我得到了-

["('1','Hello is 1)people 2)animals'), ('People are 1) hello 2) animals')"]

似乎忽略了中间括号。我该怎么做才能得到我需要的结果?

谢谢。

注意:

对于我打算用来获得所需输出的拆分功能,我得到了这个-

r = re.split(r'\((?=\').*(?<=\')\)(?=\,)', txt1)

['[', ", ('a')]"]

【问题讨论】:

    标签: python arrays regex python-3.x regex-lookarounds


    【解决方案1】:

    为什么是正则表达式?

    import ast
    [list(x) if isinstance(x, tuple) else [x] for x in ast.literal_eval(txt1)]
    # => [['1', 'Hello is 1)people 2)animals'], ['People are 1) hello 2) animals'], ['a']]
    

    如果您坚持使用正则表达式,除非字符串包含转义引号,否则这应该有效:

    [re.findall(r"'[^']*'", x) for x in re.findall(r"\(('[^']*'(?:,\s*'[^']*')*)\)", txt1)]
    # => [["'1'", "'Hello is 1)people 2)animals'"], ["'People are 1) hello 2) animals'"], ["'a'"]]
    

    【讨论】:

      【解决方案2】:

      无需使用regex的另一种解决方案:

      txt1 = "[('1','Hello is 1)people 2)animals'), ('People are 1) hello 2) animals'), ('a')]"
      replace_pairs = {
          "('": "'",
          "'), ": '#',
          '[': '',
          ']': '',
          "'": '',
      }
      for k, v in replace_pairs.items():
          txt1 = txt1.replace(k, v)
      
      txt1 = txt1[:-1].split('#') # the last char is a paranthesis
      print([i.split(',') for i in txt1])
      

      输出:

      [['1', 'Hello is 1)people 2)animals'], ['People are 1) hello 2) animals'], ['a']]
      

      注意:如果输入比您在此处显示的更复杂,这可能不起作用。

      【讨论】:

        【解决方案3】:

        您可以尝试使用模式\(([^(]+)\)

        解释:

        \( - 匹配 ( 字面意思

        (...) - 捕获组

        [^(]+ - 匹配(以外的一个或多个字符

        \) - 匹配 ) 字面意思

        并使用替换模式:[\1],它将第一个捕获组(反向引用 \1)放在方括号内。

        Demo

        【讨论】:

        • 你能解释一下 ` [^(]+ ` 在这里做什么吗?我相信这是为了检测 " ( " 字符,无论它出现多少次。但这不是用" ( " 早点?
        • @SantoshPavan 不,答案中解释:匹配来自(的一个或多个其他字符
        • 在这种情况下,它是否也适用于输入 ` ('1', 'Hello is (1) people 2)animals') `?因为它检测的是(1) people 2) animals') ,而不是检测来自` ('1', 'Hello is (1) people 2) animals') `的括号。
        • @SantoshPavan 不,因为(1) 在第一个条目中
        • 你能告诉我我提到的其他输入的正则表达式是什么吗?我想更了解它。我试图想出一个,但做不到。谢谢。
        猜你喜欢
        • 2015-09-13
        • 2021-10-11
        • 1970-01-01
        • 1970-01-01
        • 2011-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多