【发布时间】:2018-01-20 04:48:20
【问题描述】:
我在完成正则表达式教程时遇到了麻烦,该教程使用“在 my_string 中查找所有大写单词并打印结果”引用了该问题的单词,其中一些单词带有撇号。
原始字符串:
In [1]: my_string
Out[1]: "Let's write RegEx! Won't that be fun? I sure think so. Can you
find 4 sentences? Or perhaps, all 19 words?"
当前尝试:
# Import the regex module
import re
# Find all capitalized words in my_string and print the result
capitalized_words = r"((?:[A-Z][a-z]+ ?)+)"
print(re.findall(capitalized_words, my_string))
当前结果:
['Let', 'RegEx', 'Won', 'Can ', 'Or ']
我认为期望的结果是:
['Let's', 'RegEx', 'Won't', 'Can't', 'Or']
您如何从 r"((?:[A-Z][a-z]+ ?)+)" 到在 Let's, Won't 和 Can't 的末尾同时选择 's 和 't所有试图捕捉的东西都应该有一个撇号?
【问题讨论】:
-
[A-Z][a-z]+表示“A 和 Z 以及 a 和 z 之间的所有字母”。定义的范围不包括撇号。将它们添加到正则表达式中。
标签: python regex python-3.x