我需要一个正则表达式来处理从文本中提取单词时的撇号

时间:2015-09-01 05:51:22

标签: python regex text-parsing

有人知道使用正则表达式从文本中提取单词时处理撇号的方法吗?

>>> import re
>>> s = re.compile(r"\b[A-Za-z0-9_\-]+\b")
>>> s.findall("I don't know Sally's 'special' friend.")
['I', 'don', 't', 'know', 'Sally', 's', 'special', 'friend']

期望的结果:

['I', "don't", 'know', 'Sally', 'special', 'friend']

This discussion介绍了如何查找整个单词但不处理撇号。

1 个答案:

答案 0 :(得分:2)

s = re.compile(r"(?:^|(?<=\s))[A-Za-z0-9_'\-]+(?=\s|$|\b)")

使用此代替\blookarounds将适合您。请参阅演示。

https://regex101.com/r/sS2dM8/25