> s2 = "a!=b" >> re.compile("SOMTHING").split(s1) >> # I expect ['a','1'] >> re.compi-6ren">
gpt4 book ai didi

python - 正则表达式:如何按 "="拆分而不是按 "!="拆分

转载 作者:行者123 更新时间:2023-11-30 23:18:30 25 4
gpt4 key购买 nike

>> s1 = "a=b"
>> s2 = "a!=b"

>> re.compile("SOMTHING").split(s1)
>> # I expect ['a','1']

>> re.compile("SOMTHING").split(s2)
>> # I expect ['a!=1'] and NOT ['a!,'1']

我尝试了 compile([^!]=).split(s2) 但这不起作用并给出 ['','1']

我怎样才能做到这一点?

最佳答案

您可以使用 negative lookbehind assertion为了这。

>>> s1 = "a=b"
>>> s2 = "a!=b"
>>> r = re.compile(r"(?<!!)=")
>>> r.split(s1)
['a', 'b']
>>> r.split(s2)
['a!=b']

根据您的输入,您可能还需要展望 future :

>>> s3 = "a==b"  # I guess you wouldn't want to split that
>>> r.split(s3)
['a', '', 'b']
>>> r = re.compile(r"(?<![!=])=(?!=)")
>>> r.split(s3)
['a==b']

关于python - 正则表达式:如何按 "="拆分而不是按 "!="拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26708951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com