关于regex:Python-re.split:在开头和结尾处列出的多余空字符串

Python - re.split: extra empty strings that the beginning and end list

我正在尝试采用一串int和/或float并创建一个float列表。 该字符串将在其中包含这些需要忽略的括号。 我正在使用re.split,但是如果我的字符串以方括号开头和结尾,则会得到多余的空字符串。 这是为什么?

码:

1
2
3
4
5
6
import re
x ="[1 2 3 4][2 3 4 5]"
y = "1 2 3 4][2 3 4 5"
p = re.compile(r'[^\\d\\.]+')
print p.split(x)
print p.split(y)

输出:

1
2
['', '1', '2', '3', '4', '2', '3', '4', '5', '']
['1', '2', '3', '4', '2', '3', '4', '5']


如果使用re.split,则字符串开头或结尾的定界符会在结果的数组开头或结尾导致空字符串。

如果不希望这样,请将re.findall与正则表达式配合使用,该正则表达式与每个不包含定界符的序列匹配。

例:

1
2
3
4
5
import re

a = '[1 2 3 4]'
print(re.split(r'[^\\d]+', a))
print(re.findall(r'[\\d]+', a))

输出:

1
2
['', '1', '2', '3', '4', '']
['1', '2', '3', '4']

正如其他人在他们的答案中指出的那样,这可能不是解决此问题的完美方法,但这是对问题标题中描述的问题的一般回答,当我使用Google找到该问题时,我也必须解决该问题。 。


您可以使用filter避免出现空结果:

1
2
3
4
x ="[1 2 3 4][2 3 4 5]"

print filter(None, re.split(r'[^\\d.]+', x))
//=> ['1', '2', '3', '4', '2', '3', '4', '5']

作为一种更Python的方式,您可以只使用列表推导和str.isdigit()方法来检查您的字符是否为digit:

1
2
>>> [i for i in y if i.isdigit()]
['1', '2', '3', '4', '2', '3', '4', '5']

首先,关于代码,您需要根据空间或方括号([\\[\\] ]可以完成此操作)进行拆分,并摆脱用于前括号和后方括号的空字符串,您可以首先strip您的字符串:

1
2
3
4
5
6
7
8
>>> y = "1 2 3 4][2 3 4 5"
>>> re.split(r'[\\[\\] ]+',y)
['1', '2', '3', '4', '2', '3', '4', '5']
>>> y = "[1 2 3 4][2 3 4 5]"
>>> re.split(r'[\\[\\] ]+',y)
['', '1', '2', '3', '4', '2', '3', '4', '5', '']
>>> re.split(r'[\\[\\] ]+',y.strip('[]'))
['1', '2', '3', '4', '2', '3', '4', '5']

您还可以使用filter函数和bool函数包装结果。

1
2
>>> filter(bool,re.split(r'[\\[\\] ]+',y))
['1', '2', '3', '4', '2', '3', '4', '5']


您可以使用正则表达式来捕获所需的内容,而不用分割字符串。您可以使用此正则表达式:

1
(\\d+)

工作演示

enter image description here

Python代码:

1
2
3
4
5
import re
p = re.compile(ur'(\\d+)')
test_str = u"[1 2 3 4][2 3 4 5]"

re.findall(p, test_str)

1
2
3
4
5
import re
str="[1 2 3 4][2 3 4 5]"
print re.findall(r'\\d+', str)
str="1 2 3 4][2 3 4 5"
print re.findall(r'\\d+', str)