2017-05-23 30 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()