python - 正则表达式查找一个或多个字符,包括中间带有句号、撇号或连字符的字符。如果最后一个符号仅在末尾出现一次,则没有最后一个符号

标签 python regex

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+\.?)?

RegEx Demo

正则表达式详细信息:

  • \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/

相关文章:

php - 如何将字符串中的每个 URL 替换为另一个唯一的 URL?

javascript - 从该字符串中提取该特定数值的正则表达式是什么?

python - 如何从 Django Headers 获取数据?

python - 根据组编号将数组数组排序

python - 有效地在不同尺寸上使用模板匹配

java - 使用Java String split时出错

python - Python 中 Win32_ComputerSystem 的 __name__ 属性?

python - 构建一个包含冒号的元组以用于索引 numpy 数组

javascript - 如何在带有字符串变量的mongoDB查询中使用$regex?

c# - 检索带空格的字母表