我有下面的字符串,我想分成一个列表。我想知道如何在前面和后面有空格的数字上拆分它。你知道吗
我试过以下方法,几乎就是我所需要的。你知道吗
\s+(?=\d)|(?<=\d)\s+
import re
# Find the numeric values:
tmplist = re.split(r'\s+(?=\d)|(?<=\d)\s+', 'Dual 425mm AutoCannon 25')
# Print the list
print(tmplist)
结果如下:
['Dual', '425mm AutoCannon', '25']
这是期望的结果:
['Dual 425mm AutoCannon', '25']
一种方法是匹配一个空格,并使用正向前瞻来断言右边的数字是1+个数字,之后是非空格字符:
\s
空白字符(?=
正面展望,断言右边的内容\d+
匹配1+个数字(?!
负面展望,断言右边的不是\S
匹配非空白字符)
关闭负面展望Regex demo| Python demo
您的代码可能如下所示:
结果
参见regulex视觉
不完全是最漂亮的,但由于正则表达式有时很难阅读,或者返回并记住为什么要这样做,这里有一个函数可以完成您正在尝试做的事情。我把你的文字扩展了一点,只是为了确保它能继续工作。你知道吗
相关问题 更多 >
编程相关推荐