2017-05-23 54 views
-3

我需要根據Python3中的正則表達式來識別任何字符串中的子字符串。python3中的正則表達式子串

例如,採取以下字符串:

It sent a notice of delivery of goods: UserName1 
Sent a notice of delivery of the goods: User is not found, UserName2 
It sent a notice of receipt of the goods: UserName1 
It sent a notice of receipt of the goods: User is not found, UserName2 

我想冒號後得到的文本

結果:

UserName1 
User is not found, UserName2 
UserName1 
User is not found, UserName2 

我要求幫助寫一個正則表達式。 感謝您的幫助!

+0

你沒有任何tryied。我建議你先看看 - > docs.python.org/2/library/re.html。然後嘗試構建一個正則表達式。如果你遇到正則表達式的問題,向我們展示你的正則表達式,社區將幫助你。下面是一個示例python正則表達式的工作原理:https://developers.google.com/edu/python/regular-expressions –

+0

爲什麼不str.split(':')並完全避免了正則表達式 – Ludisposed

+0

我寧願與[ str.find](https://docs.python.org/3.6/library/stdtypes.html#str.find)和字符串切片,不需要分割每個':' –

回答

0

無需正則表達式在這裏,你可以split\n:,即:

text = """It sent a notice of delivery of goods: UserName1 
Sent a notice of delivery of the goods: User is not found, UserName2 
It sent a notice of receipt of the goods: UserName1 
It sent a notice of receipt of the goods: User is not found, UserName2""" 

for x in text.split("\n"): 
    print(x.split(": ")[1]) 

如果你喜歡一個正則表達式,並避免上線多:,你的文字可以使用:

for x in text.split("\n"): 
    print(re.split(".*: ", x)[1]) 

輸出:

UserName1 
User is not found, UserName2 
UserName1 
User is not found, UserName2 
+0

這會截斷輸出,如果多個':' '每行存在 –

+0

OP提供的例子不包含多個':',我的答案是基於這個的。 –

0
S[S.find(':') + 1:].strip() 

,或者如果你需要的最後一次出現 ':'

S[S.rfind(':') + 1:].strip()