5

我需要正则表达式或 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

我实际上已经阅读过正则表达式,但它对我来说非常陌生。谢谢。

4

3 回答 3

9

我建议使用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'
于 2013-05-01T06:45:17.127 回答
6
>>> s="A:01 What is the date of the election ?"
>>> s.split(" ", 1)[1].rsplit(" ", 1)[0]
'What is the date of the election'
>>> 
于 2013-05-01T06:54:36.007 回答
3

如果这就是您所需要的,则无需深入研究正则表达式;您可以使用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(':')
于 2013-05-01T06:42:47.523 回答