re.findall(r'[A-Za-z]+(?=\'|\.|\-[A-Za-z]+)?', txt)
re.findall(r'[A-Za-z\.\-]+(?:\'[A-Za-z]+)?',txt)
输入
txt = "which would find I'm U.S. co-op, include ending. without the . , but not ' - . rd- "
预期输出
['which', 'would', 'find', "I'm", "U.S.", 'co-op', 'include', 'ending', 'without', 'the', 'but', 'not', 'rd']
我尝试了上述方法和变体,但无法使其工作。怎么做?
最佳答案
您可以使用此正则表达式使用 findall
进行匹配:
\w+(?:['.-]\w+\.?)?
正则表达式详细信息:
\w+
:匹配 1 个以上单词字符(?:['.-]\w+\.?)?
:以'
或开头的可选非捕获组。
或-
后跟 1 个以上单词字符和可选的尾随点。
代码:
import re
txt = "which would find I'm U.S. co-op, include ending. without the . , but not ' - . rd- "
print (re.findall(r"\b\w+(?:['.-]\w+\.?)?", txt))
['which', 'would', 'find', "I'm", 'U.S.', 'co-op', 'include', 'ending', 'without', 'the', 'but', 'not', 'rd']
关于python - 正则表达式查找一个或多个字符,包括中间带有句号、撇号或连字符的字符。如果最后一个符号仅在末尾出现一次,则没有最后一个符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67250405/