I'm trying to split a string looking like this in Python using re.split:
我在用re.split:
#NAME="Foo" NAME2="foobar" NAME3="BAR BAR"
comp = "NAME=\"Foo\" NAME2=\"FOO BAR\" NAME3=\"BAR BAR\""
This is how my split-function including regex looks like:
这就是我的split函数包括regex的样子:
re.split('(\s\w+\=\".*?\")', comp)
The result looks like this:
结果是这样的:
['NAME="Foo"', 'NAME2="foobar"', '', 'NAME3="BAR BAR"', '']
While this is correct I'd like to get rid of all empty elements.
虽然这是正确的,但我想去掉所有的空元素。
2 个解决方案
#1
8
Is this what you're looking for:
这就是你要找的:
In [10]: re.findall(r'\w+=".*?"', comp)
Out[10]: ['NAME="Foo"', 'NAME2="FOO BAR"', 'NAME3="BAR BAR"']
?
吗?
It doesn't sound like re.split()
is the right tool for the job.
它听起来不像是re.split()是适合这个任务的工具。
#2
2
You can also use a list comprehension and filter it directly
您还可以使用列表理解并直接过滤它
l = [x for x in re.split('(\s\w+\=\".*?\")', comp) if x != '']
The result looks like what you expect:
结果看起来就像你期望的那样:
print l
['NAME="Foo"', ' NAME2="FOO BAR"', ' NAME3="BAR BAR"']
#1
8
Is this what you're looking for:
这就是你要找的:
In [10]: re.findall(r'\w+=".*?"', comp)
Out[10]: ['NAME="Foo"', 'NAME2="FOO BAR"', 'NAME3="BAR BAR"']
?
吗?
It doesn't sound like re.split()
is the right tool for the job.
它听起来不像是re.split()是适合这个任务的工具。
#2
2
You can also use a list comprehension and filter it directly
您还可以使用列表理解并直接过滤它
l = [x for x in re.split('(\s\w+\=\".*?\")', comp) if x != '']
The result looks like what you expect:
结果看起来就像你期望的那样:
print l
['NAME="Foo"', ' NAME2="FOO BAR"', ' NAME3="BAR BAR"']