用两个不同的字符拆分字符串

Splitting a string with two different characters

我有以下字符串

u'root\n |-- date: string (nullable = true)\n |-- zip: string (nullable = true)\n' 

我想提取列名。列名前面有 |--,后面有 :

我可以分两个阶段进行:

s = u'root\n |-- date: string (nullable = true)\n |-- zip: string (nullable = true)\n' 
s = s.split('|-- ')
s = s.split(':')

但是,我想知道是否有办法同时拆分两个字符。

您可以使用 re.findall 同时获取它们:

>>> import re
>>> data = u'root\n |-- date: string (nullable = true)\n |-- zip: string (nullable = true)\n'
>>> re.findall(r'\|--\s(\w+):', data)
['date', 'zip']
>>>

下面是对所用正则表达式模式的解释:

\|--   # Matches |--
\s     # Matches a whitespace character
(\w+)  # Capture group for one or more word characters
:      # Matches :

如果您只想拆分名称然后提取,则使用 findall 而不是拆分,效率低于仅使用 findall:

所以基于我想提取列名。列名前面有 |--,后面有 :。

import re

s = u'root\n |-- date: string (nullable = true)\n |-- zip: string (nullable = true)\n'
print(re.findall(r"\|--\s+(.*?):",s))
['date', 'zip']

或使用re.compile:

patt = re.compile(r"\|--\s+(.*?):")
patt.findall(s)
['date', 'zip']

无法使用两个分隔符进行拆分 str.split

如果您要使用 str.split,您可以这样做:

print([x.split(":")[0] for x in s.split("|-- ")[1:]])
['date', 'zip']

初始拆分后,子拆分中的第一个元素将始终是带有 : 的元素,但如果您在其他地方有任何其他 |-- 不是您想要的周围数据,则此方法将会中断。

However, I wanted to know if there is a way to split with two characters at once.

可以使用 re#split:

re.split(r'\|--|:', your_string)