使用regex使用单冒号而不是双冒号拆分

2024-09-24 22:26:13 发布

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

我有一根这样的绳子

"yJdz:jkj8h:jkhd::hjkjh"

我想用冒号作为分隔符,但不要用双冒号。预期结果:

("yJdz", "jkj8h", "jkhd::hjkjh")

我在尝试:

re.split(":{1}", "yJdz:jkj8h:jkhd::hjkjh")

但我得到了一个错误的结果。

同时,我用string.replace("::", "$$")转义"::"


Tags: restring错误replacesplit分隔符绳子冒号
2条回答

如果需要,可以使用lookahead and lookbehind完成此操作:

>>> s = "yJdz:jkj8h:jkhd::hjkjh"
>>> l = re.split("(?<!:):(?!:)", s)
>>> print l
['yJdz', 'jkj8h', 'jkhd::hjkjh']

这个正则表达式实质上是说“匹配一个:,后面没有:,前面没有:

你可以在(?<!:):(?!:)上分开。这使用了两个negative lookarounds(lookbehind和lookahead),它们断言有效匹配只有一个冒号,在它之前或之后没有冒号。

为了解释这种模式:

(?<!:)  # assert that the previous character is not a colon
:       # match a literal : character
(?!:)   # assert that the next character is not a colon

两个lookaround都是必需的,因为如果只有lookbehind,那么正则表达式引擎将匹配::中的第一个冒号(因为前一个字符不是冒号),如果只有lookahead,那么第二个冒号将匹配(因为下一个字符不是冒号)。

相关问题 更多 >