2013-05-01 34 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' 
>>> 
相關問題