在Python中多次执行Regex Lookahead和Lookahead

2024-04-18 04:25:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我的输入格式如下(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和Lookahead来避免被数字分割-'1'或'2',这在前面我使用一个简单的re.split('[\(\)\[\]]语句时发生过

我一直在尝试一个findall函数来检查我得到了什么。你知道吗

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

我已经得到-

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

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

谢谢你。你知道吗

注意:

对于split函数,我打算用它来获得所需的输出,我得到这个-

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

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


Tags: 函数rehellois格式peopleare括号
3条回答

为什么是regex?你知道吗

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'"]]

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

说明:

\(-按字面意思匹配(

(...)-捕获群

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

\)-按字面意思匹配)

并使用replace模式:[\1],它将第一个捕获组(backreference\1)放在方括号内。你知道吗

Demo

不必使用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']]

注意:如果输入比这里显示的更复杂,这可能不起作用。你知道吗

相关问题 更多 >