python 正则表达式: use first blank as sep but maintain rest of blank sequence

标签 python regex whitespace

我现在在这个正则表达式上争论得太久了。 分割应使用空白作为分隔符 但将剩余的保留在下一个标记的空白序列中

'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/

相关文章:

javascript - 如何删除 ionic 2 中的开始/结束空格

.htaccess - htaccess 带空格的文件名损坏

python - 无法让 twemproxy 与 Python redis 一起工作

python - 在 Pandas 中一次在列中显示常用值

Python 困惑 : Set display?

css - 如何删除具有特定前缀的所有类(使用 Visual Studio Code)?

Python:解析具有各种字段计数的冒号分隔文件

java - 删除 Java 字符串中给定模式的表行

c# - 如何找到某个子字符串后特定类型字符首次出现的索引?

html - 如何在 HTML 和 CSS 中删除图像和资源管理器侧面之间的 "whitespace"