Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
正则表达式:python中的文本字符串,并拆分为数组_Python_Regex - Fatal编程技术网

正则表达式:python中的文本字符串,并拆分为数组

正则表达式:python中的文本字符串,并拆分为数组,python,regex,Python,Regex,我需要拆分一个文本,如下所示: //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) 但它还没有准备好打破,即使我尝试了类似的东西 重新编

我需要拆分一个文本,如下所示:

//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]”)。拆分


如果有人能解释一下这一点?

您可以使用带有前瞻正则表达式的
findall
,如下所示:

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


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

您可以将
findall
与前瞻正则表达式一起使用,如下所示:

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


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

虽然
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']
s='CS-135IntrotoComputingCS-154IntroToWonderLand'
x=[i.start()代表re.finditer('CS',s)]#以获取'CS'的起始位置
计数=0
l=[]

虽然count+1虽然
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']
s='CS-135IntrotoComputingCS-154IntroToWonderLand'
x=[i.start()代表re.finditer('CS',s)]#以获取'CS'的起始位置
计数=0
l=[]

虽然count+1感谢了很多@anubhava,但它成功了!唯一的问题是,当我有CS-135IntrotoCS时,它会断开,然后在这种情况下,它会再次将CS标记为数组的不同成员!你能更新你的问题并给我显示输入字符串和预期的输出吗。你可以使用:
re.findall(r'.+?(?=CS-|$)',s)
非常感谢@anubhava,它成功了!唯一的问题是,当我有CS-135IntrotoCS时,它会断开,然后在这种情况下,它会再次将CS标记为数组的不同成员!你能更新你的问题并给我显示输入字符串和预期的输出吗。您可以使用:
re.findall(r.+?(?=CS-|$)”,s)
如何将
135IntrotoComputingCS
转换为
-135 introtocomputing
?(除非它们都是“x简介”格式,我不这么认为)你从哪里得到这些数据?也许你可以用更好的格式。你打算如何将
135IntrotoComputingCS
转换成
-135 introtocomputing
?(除非它们都是“x简介”格式,我不这么认为)你从哪里得到这些数据?也许你可以用更好的格式。