我现在在这个正则表达式上争论得太久了。 分割应使用空白作为分隔符 但将剩余的保留在下一个标记的空白序列中
'123 45 678 123.0'
=>
'123', '45', ' 678', ' 123.0'
我的数字也是 float ,组数未知。
最佳答案
使用后向断言怎么样?:
>>> import re
>>> regex = re.compile(r'(?<=[^\s])\s')
>>> regex.split('this is a string')
['this', ' is', 'a', ' string']
正则表达式分割:
(?<=...) #lookbehind. Only match if the `...` matches before hand
[^\s] #Anything that isn't whitespace
\s #single whitespace character
在英语中,这翻译为“如果前面没有空白字符,则匹配单个空白字符。”
或者您可以使用否定的lookbehind断言:
regex = re.compile(r'(?<!\s)\s')
这可能稍微好一些(如评论中所建议的),并且应该相对容易弄清楚它是如何工作的,因为它与上面非常相似。
关于 python 正则表达式: use first blank as sep but maintain rest of blank sequence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13531985/