Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python re.findall() Capitalized Words including Apostrophes

I'm having trouble completing the a regex tutorial that went \w+ references words to this problem with "Find all capitalized words in my_string and print the result" where some of the words have apostrophes.

Original 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?"

Current Attempt:

# 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))

Current Result:

['Let', 'RegEx', 'Won', 'Can ', 'Or ']

What I think the desired outcome is:

['Let's', 'RegEx', 'Won't', 'Can't', 'Or']

How do you go from r"((?:[A-Z][a-z]+ ?)+)" to also selecting the 's and 't at the end of Let's, Won't and Can't when not everything were trying to catch is expected to have an apostrophe?

like image 781
BrightHalo Avatar asked Feb 10 '26 17:02

BrightHalo


1 Answers

Just add an apostrophe to the second bracket group:

capitalized_words = r"((?:[A-Z][a-z']+)+)"
like image 83
James Avatar answered Feb 13 '26 08:02

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!