Python/Regex:如果线确实包含某个特殊字符,则拆分字符串



我正在尝试在字符上拆分多行字符串,但前提是该行不包含:。不幸的是,我看不到使用re.split()的简便方法,对字符:进行负回回本,因为:可能发生在字符串早期的另一行中。

作为一个例子,我想在)上拆分以下字符串。

字符串:

Hello1 (
First : (),
Second )
Hello2 (
First 
)

输出:

['Hello1 (nFirst : (),nSecond', 'Hello2 (nFirst n']

可以使用Python,尽管与本机re模块不是"开箱即用"。

第一个替代品

新的 regex模块支持可变的lookbehind,因此您可以使用

(?<=^[^:]+))
# pos. lookbehind making sure there's no : in that line


Python中:

import regex as re
data = """
Hello1 (
First : (),
Second )
Hello2 (
First 
)"""
pattern = re.compile(r'(?<=^[^:]+))', re.MULTILINE)
parts = pattern.split(data)
print(parts)

产生

['nHello1 (nFirst : (),nSecond ', 'nnHello2 (nFirst n', '']


第二个替代品

另外,您可以匹配有关行,然后让它们在(*SKIP)(*FAIL)之后失败:

^[^:n]*:.*(*SKIP)(*FAIL)|)
# match lines with at least one : in it
# let them fail
# or match )


再次在Python中:

pattern2 = re.compile(r'^[^:n]*:.*(*SKIP)(*FAIL)|)', re.MULTILINE)
parts2 = pattern.split(data)
print(parts2)

请参阅在Regex101.com上的后者上的演示。


第三替代

好吧,现在答案比以前想象的要长。您甚至可以在功能的帮助下使用本机re模块进行操作。在这里,您需要首先替换有关)并由替代者分开:

def replacer(match):
    if match.group(1) is not None:
        return "SUPERMAN"
    else:
        return match.group(0)
pattern3 = re.compile(r'^[^:n]*:.*|())', re.MULTILINE)
data = pattern3.sub(replacer, data)
parts3 = data.split("SUPERMAN")
print(parts3)

最新更新