regex将python中的文本字符串拆分为数组

2024-09-27 07:32:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要像这样分割一段文字:

//string
s = CS -135IntrotoComputingCS -154IntroToWonderLand...

阵列状

inputarray[0]= CS -135 Intro to computing
inputarray[1]= CS -154 Intro to WonderLand
.
.

是的。 等等; 我试着这样做:

re.compile("[CS]+\s").split(s)

但它还没有准备好甚至打破,即使我尝试类似的东西

重新编译(“[CS]”).split(s)

如果有人能解释一下


Tags: torestringcssplit文字compileintro
2条回答

虽然findall更简单,但是这里也可以使用finditer

s = 'CS -135IntrotoComputingCS -154IntroToWonderLand'
x=[i.start() for i in re.finditer('CS ',s)] # to get the starting positions of 'CS'
count=0
l=[]
while count+1<len(x):
    l.append(s[x[count]:x[count+1]])
    count+=1
l.append(s[x[count]:])
print(l) # ['CS -135IntrotoComputing', 'CS -154IntroToWonderLand']

可以将findall与lookahead regex一起使用,如下所示:

>>> s = 'CS -135IntrotoComputingCS -154IntroToWonderLand'
>>> print re.findall(r'.+?(?=CS|$)', s)

['CS -135IntrotoComputing', 'CS -154IntroToWonderLand']

正则表达式:.+?(?=CS|$)匹配1+任何在下一个位置或行尾有CS的字符

相关问题 更多 >

    热门问题