2013-05-01 921 views
4

我需要正则表达式或Python中的帮助才能从一组字符串中提取子字符串。该字符串由字母数字组成。我只想要在第一个空格之后开始的子字符串,并在下面给出的示例的最后一个空格之前结束。在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 

给出的那些其实我看了一下正则表达式字符串中提取日期或日期等,但它是非常陌生的我。谢谢。

回答

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' 
+0

谢谢!你的代码不需要使用正则表达式就可以完成我所需要的功能。我正在尝试正则表达式,但没有运气。 – Cryssie 2013-05-01 07:02:27

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(':') 
+5

不使用'_',只是使用'theReallyAwesomeDay = s.partition(':')[2]' – 2013-05-01 06:44:41

+0

@gnibble r - 我认为'_'更清晰,尤其是因为通常做'start,_,end = s.partition(':')'(所以最终只遵循相同的形式) – sapi 2013-05-01 09:06:16

+0

使用'_'作为'gettext'的别名也很常见 – 2013-05-01 09:08:54

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' 
>>> 
相关问题