我在regex或Python中需要帮助从一组字符串中提取子字符串。该字符串由字母数字组成。我只想要在第一个空格之后开始并在最后一个空格之前结束的子字符串,如下面给出的示例。
Example 1:
A:01 What is the date of the election ?
BK:02 How long is the river Nile ?
Results:
What is the date of the election
How long is the river Nile
当我在它的时候,是否有一种简单的方法可以在某个角色之前或之后提取字符串?例如,我想从类似于示例2中给出的字符串中提取日期或日期。
Example 2:
Date:30/4/2013
Day:Tuesday
Results:
30/4/2013
Tuesday
我实际上已经阅读了有关正则表达式但它对我来说非常陌生。感谢。
答案 0 :(得分:6)
我建议使用split
>>> s="A:01 What is the date of the election ?"
>>> " ".join(s.split()[1:-1])
'What is the date of the election'
>>> s="BK:02 How long is the river Nile ?"
>>> " ".join(s.split()[1:-1])
'How long is the river Nile'
>>> s="Date:30/4/2013"
>>> s.split(":")[1:][0]
'30/4/2013'
>>> s="Day:Tuesday"
>>> s.split(":")[1:][0]
'Tuesday'
答案 1 :(得分:5)
>>> s="A:01 What is the date of the election ?"
>>> s.split(" ", 1)[1].rsplit(" ", 1)[0]
'What is the date of the election'
>>>
答案 2 :(得分:1)
如果这就是你所需要的,就没有必要深入研究正则表达式;你可以使用str.partition
s = "A:01 What is the date of the election ?"
before,sep,after = s.partition(' ') # could be, eg, a ':' instead
如果你想要的只是最后一部分,你可以使用_
作为“不关心”的占位符:
_,_,theReallyAwesomeDay = s.partition(':')