【问题标题】:RegEx - Parsing name and last name from a stringRegEx - 从字符串中解析姓名和姓氏
【发布时间】:2021-11-16 16:08:34
【问题描述】:

我正在尝试从 Outlook“to”约定中的字符串解析名称和姓氏的所有实例,并将每个实例保存在 python 列表中。我正在使用 Python 3.6.4。
例如,我想要以下字符串:

“致:约翰·列侬 \b002; Paul McCartney \b002;"

要解析成:

['约翰列侬','保罗麦卡特尼']

我使用Replace all words from word list with another string in python作为参考,并想出了这个代码:

import re
prohibitedWords = [r'to:',r'To:','\b002',"\<(.*?)\>"]
mystring = 'To: John Lennon <John.Lennon@gmail.com> \b002; Paul McCartney <Paul.McCartney@yahoo.com> \b002;'
big_regex = re.compile('|'.join(prohibitedWords))
the_message = big_regex.sub("", str(mystring)).strip()
print(the_message)

但是,我得到以下结果:

John Lennon  ; Paul McCartney  ;

这不是最优的,因为我得到了很多我无法解析的空间。此外,我觉得这不是最佳方法。 感谢任何建议。
谢谢

【问题讨论】:

  • 也许使用re.findall('(?:\\bto:|\b002;)\s*(.*?)\s*&lt;', mystring, re.I)?

标签: python regex string


【解决方案1】:

使用 re.sub 并使用这些部分创建一个替换 [r'to:',r'To:','\b002',"\&lt;(.*?)\&gt;"] 您将用空字符串替换匹配项。

如果您要删除的所有字符都消失了,您将得到一个字符串John Lennon Paul McCartney,就像在这个Python example 中一样,如果您想拆分,您不知道哪个部分属于哪里。

同时删除周围的空白字符可能会在删除它们时导致意外的间隙或串联结果。

您可以通过匹配可能的前导部分来使匹配更加具体,并捕获您想要的部分而不是替换。

(?:\\b[Tt]o:|\b002;)\s*(.+?)\s*<[^<>@]+@[^<>@]+>
  • (?:\\b[Tt]o:|\b002;) 匹配 To to 或退格字符和 002
  • \s* 匹配可选的空白字符
  • (.+?) 在第 1 组中捕获 1 个或多个字符
  • \s* 匹配可选的空白字符
  • &lt;[^&lt;&gt;@]+@[^&lt;&gt;@]+&gt; 匹配标签之间的单个@

查看regex demo 和Python demo。

例如

import re

pattern = "(?:\\b[Tt]o:|\b002;)\s*(.+?)\s*<[^<>@]+@[^<>@]+>"
mystring = 'To: John Lennon <John.Lennon@gmail.com> \b002; Paul McCartney <Paul.McCartney@yahoo.com> \b002;'
print(re.findall(pattern, mystring))

输出

['John Lennon', 'Paul McCartney']

【讨论】:

  • \b in \b002; 是一个退格字符。 OP 有一个简单的字符串文字,而不是原始文字。
  • @WiktorStribiżew 所以\b 在没有r' 的情况下阅读r' 在正则表达式和mystring 中都会变成\x08,就像"(?:\\b[Tt]o:|\b002;)\s*(.+?)\s*&lt;[^&lt;&gt;@]+@[^&lt;&gt;@]+&gt;" 一样,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-07
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 2014-03-04
  • 2016-02-22
相关资源
最近更新 更多