结合负前瞻和正则表达式

时间:2012-12-27 20:16:45

标签: python regex negative-lookahead negative-lookbehind

我想要一个正则表达式,它会在每"."分割一个字符串,除非"."前面有一个数字后面跟着一个数字。例如:

"hello world.foo 1.1 bar.1" ==> ["hello world","foo 1.1 bar", "1"]

我目前有:

"(?<![0-9])\.(?!\d)" 

但它给出了:

["hello world", "foo 1.1 bar.1"]

但它没有找到最后一个"."有效。

4 个答案:

答案 0 :(得分:3)

非|的方法:

(?<![0-9](?=.[0-9]))\.

答案 1 :(得分:1)

如果.前面没有数字,或者数字没有成功,则在In [18]: re.split(r'(?<!\d)\.|\.(?!\d)', text) Out[18]: ['hello world', 'foo 1.1 bar', '1'] 上拆分:

{{1}}

答案 2 :(得分:1)

那是因为只有其中一个断言必须失败才能使整个表达式失败。试试这个:

"(?<![0-9])\.|\.(?!\d)"

答案 3 :(得分:0)

为了提供最短的解决方案,这里是我的:

(这只是@ysth的解决方案,只需稍作调整即可)

(?<!\d(?=.\d))\.

working fiddle