python - 用于在所有空格处拆分的正则表达式 Python

标签 python regex

<分区>

Possible Duplicate:
Split string on whitespace in python

我有这样一个字符串:

['.text      0x1000       0xb51b       0xb600       6.259216    ']

我想把它分成这样:

[.text, 0x1000, 0xb51b... etc]

到目前为止,我已经尝试过: re.split("( )", b) 和 re.split("[\t]", b)

但无济于事。我得到这样的东西:

.['.text', ' ', '0x1000', ' ', '0xb51b', ' ', '0xb600', ' ', '6.259216', ' ', '']

或其他一些有更多空格的。我知道我可以从字符串中删除空格,但我更愿意直接使用 RE 来首先拆分它们。

最佳答案

为什么不直接使用常规的 str.split

'.text      0x1000       0xb51b       0xb600       6.259216    '.split()

引用文档:

if sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.


顺便说一句,我发现使用 mystring.split(None)(相对于 mystring.split())有时非常有用请记住,因为它允许您不对拆分算法进行“硬编码”。

关于python - 用于在所有空格处拆分的正则表达式 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12783224/

相关文章:

c - 为什么 posix c 中的 regexec() 总是返回第一个匹配项,它如何返回所有匹配位置只运行一次?

php - 行不更新

regex - 为什么这个正则表达式同时捕获名字和中间名

mysql - PCRE Regex - 替换序列化字符串中的 URL

正则表达式查找 CamelCase 字符串和破折号,替换为 lowercase_underscored

python - Tensorflow Lite - ValueError : Cannot set tensor: Dimension mismatch

python - Flask + Gunicorn + Nginx + Supervisor 非默认端口号

python - 如何从手绘电路的扫描图像中检测逻辑门?

python - 如何使用 pandas 模块合并(即 'concat' )100+ .csv 文件?

python - 损失函数的正确做法