[英]Find consecutive capitalized words in a string, including apostrophes
我正在使用正則表達式來查找所有連續單詞都大寫的實例,並且其中一些連續單詞包含撇號,即(“母女面包店 Molly's Munchies 成立於 2009 年”)。 我已經寫了幾行代碼來做到這一點:
string = "The mother-daughter bakery, Molly’s Munchies, was founded in 2009"
test = re.findall("([A-Z][a-z]+(?=\s[A-Z])(?:\s[A-Z][a-z]+)+)", string)
print(test)
問題是我無法打印結果('Molly's Munchies')
相反,我的 output 是:
('[]')
所需的 output:
("Molly's Munchies")
任何幫助表示贊賞,謝謝!
您可以在 python 中使用此正則表達式:
r"\b[A-Z][a-z'’]*(?:\s+[A-Z][a-z'’]*)+"
正則表達式詳細信息:
\b
: 單詞匹配[AZ]
: 匹配大寫字母[a-z'']*
: 匹配 0 個或多個包含小寫字母或'
或'
字符(?:\s+[AZ][a-z'']*)+
匹配 1 個或多個這樣的大寫字母單詞您需要在定義“單詞”的兩個地方添加它。 您只在一個地方添加了它。
string = "The Cow goes moo, and the Dog's Name is orange"
# e.g. both here and here
# v v
print(re.findall("([A-Z][a-z']+(?=\s[A-Z])(?:\s[A-Z][a-z']+)+)", string))
['The Cow', "Dog's Name"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.