简体   繁体   English

Python正则表达式split()字符串

[英]Python regular expression split() string

I'm quite new to regular expression in python. 我对python中的正则表达式很新。 I have the following string and want to split them into five categories. 我有以下字符串,并希望将它们分为五个类别。 I just use the split() but it will just split according to white spaces. 我只是使用split()但它会根据空格分开。

s = "1 0 A10B 1/00 Description: This is description with spaces"
sp = s.split()
>>> sp
["1", "0", "A10B", "1/00", "Description:", "This", "is", "description", "with", "spaces"]

How can I write a regular expression to make it split like this: 如何编写正则表达式使其像这样拆分:

 ["1", "0", "A10B", "1/00", "Description: This is description with spaces"]

Can somebody help please? 有人可以帮忙吗? Thanks! 谢谢!

您可以简单地指定一些拆分:

s.split(' ', 4)

The second argument to split() is the maximum number of splits to perform. split()的第二个参数是要执行的最大拆分数。 If you set this to 4, the remaining string will be item 5 in the list. 如果将此值设置为4,则剩余的字符串将是列表中的第5项。

 sp = s.split(' ', 4)

Not a perfect solution. 不完美的解决方案。 But for a start. 但是一开始。

>>> sp=s.split()[0:4]
>>> sp.append(' '.join(s.split()[4:]))
>>> print sp
['1', '0', 'A10B', '1/00', 'Description: This is description with spaces']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM