尝试将字符串分成两部分。
#Need to get 'I1234' and 'I56/I78'
name1 = 'I1234/I56/I78'
#Need to get '\I1234 ' and 'I56/I78'
name2 = '\I1234 /I56/I78'
#Need to get '\I1234 ' and '\I56 /I78'
name3 = '\I1234 /\I56 /I78'
#Need to get '\1234 ' and '\I56 /\I78 '
name4 = '\I1234 /\I56 /\I78 '
我试过了,成功了:
pat_a = re.compile(r'(.+)(/)(.+)')
Is there a better way ?
result = re.findall(pat_a, name2[::-1])
编辑
可能还有更复杂的字符串,例如:
\I78_[0]/abcd_/efg_ /I1234/I56
最佳答案
不确定是否更好,但您可以使用 partition
或 split
并设置 maxsplit=1 以避免 re
模块导入:
print('I1234/I56/I78'.partition("/")) # ('I1234', '/', 'I56/I78')
print('I1234/I56/I78'.split("/",1)) # ['I1234', 'I56/I78']
对于 partition
,您需要查看元组的第 0 个和第 2 个索引:
first, _ , last = 'I1234/I56/I78'.partition("/")
独库:
- https://docs.python.org/3/library/stdtypes.html#str.partition
- https://docs.python.org/3/library/stdtypes.html#str.split
完整示例:
name1 = 'I1234/I56/I78'
name2 = '\I1234 /I56/I78'
name3 = '\I1234 /\I56 /I78'
name4 = '\I1234 /\I56 /\I78 '
for n in [name1,name2,name3,name4]:
print(n.partition("/")) # ('I1234', '/', 'I56/I78')
print(n.split("/",1)) # ['I1234', 'I56/I78']
输出(反斜杠被转义 - 这就是它们加倍的原因):
('I1234', '/', 'I56/I78') # using partition
['I1234', 'I56/I78'] # using split
('\\I1234 ', '/', 'I56/I78') # partition
['\\I1234 ', 'I56/I78'] # split .. etc.
('\\I1234 ', '/', '\\I56 /I78')
['\\I1234 ', '\\I56 /I78']
('\\I1234 ', '/', '\\I56 /\\I78 ')
['\\I1234 ', '\\I56 /\\I78 ']
关于python - 使用正则表达式对给定的字符串进行分区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55445651/