python 中不以连字符开头的单词的正则表达式

regular expression for words that don't start with hyphen in python

我需要为 python 中的单词做正则表达式。我得到一个句子,我需要检查其中是否有单词。

单词 'Hello',“It's”将出现在列表中。单词“--Mom”或“-Mom”不在列表中。但是 'Mom' 会在列表中,因为它将 '-' 与 'Mom' 分开,所以 'Mom' 考虑 'Word' 我怎样才能得到以“-”开头的单词而不是像“--妈妈”这样的 'Word'?

def getWord():
  return"((^[A-Z])?[a-z]+)((\-[a-z]*)*)(\')?[a-z]{0,2}"

text=r"""Hello Bob! It's Mary, your mother-in-law, the mistake is your parents'! --Mom""")
com = re.compile(rf"""((?P<WORD>{getWord()})), """,re.MULTILINE | re.IGNORECASE | re.VERBOSE | re.UNICODE)

lst=[(v, k) for match in com.finditer(text)
                for k, v in match.groupdict().items()
                if v is not None and k != 'SPACE']
print(lst)

您可能过于复杂了,正则表达式查找 \w+ 上的所有搜索已经接近您在这里想要的结果。为了允许所有格,只需将 's 作为每个单词后的可选结尾。此外,为了排除前面没有空格的单词(或位于字符串的最开头),我们可以在前面加上负向回顾 (?<!\S).

text = "Hello Bob! It's Mary, your mother-in-law, the mistake is your parents! --Mom"
words = re.findall(r"(?<!\S)\w+(?:'s)?", text)
print(words)

这会打印:

['Hello', 'Bob', "It's", 'Mary', 'your', 'mother', 'in', 'law', 'the', 'mistake', 'is',
 'your', 'parents']