【问题标题】:Regex substring in python3python3中的正则表达式子字符串
【发布时间】:2017-05-23 12:37:59
【问题描述】:

我需要根据 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

我在编写正则表达式时寻求帮助。 感谢您的帮助!

【问题讨论】:

  • 你没有尝试过任何东西。我建议你先看看 -> docs.python.org/2/library/re.html 。然后尝试构建一个正则表达式。如果您对正则表达式有疑问,请向我们展示您的正则表达式,社区会为您提供帮助。以下是 python 中的正则表达式如何工作的示例:developers.google.com/edu/python/regular-expressions
  • 为什么不使用 str.split(':') 并完全避免使用正则表达式
  • 我宁愿使用str.find 和字符串切片,不需要在每个':'上分割

标签: python regex python-3.x


【解决方案1】:

这里不需要正则表达式,你可以在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

【讨论】:

  • 这会截断输出,如果每行存在多个':'
  • OP提供的示例不包含多个:,我的回答是基于此。
【解决方案2】:
S[S.find(':') + 1:].strip()

或者如果您需要最后一次出现 ':'

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

【讨论】:

    猜你喜欢
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多