![](/img/trans.png)
[英]Python Regex to match a all variations of a keyword except if preceded by a capitalized word
[英]Python Regex match only where every word is capitalized
我想匹配所有單詞都被限制的所有字符串。
目前我嘗試過這樣的事情:
list = ["This sentence should Not Match", "This Should Only Match"]
match = []
for l in list:
x = re.search("^[A-Z]*.", l)
if x:
match.append(l)
例如,我希望正則表達式只匹配:“這是一個很好的例子在這里”,但它不應該匹配:“像這樣的東西”,“這里是一個不應該匹配的例子”,“TiHiS SeNtEnEcE”或者“這不應該匹配.Foo”
我正在循環播放大量新聞文章並嘗試匹配所有標題。 這些標題通常都是大寫的。
你可以沒有正則表達式:
l = ["This sentence should Not Match", "This Should Only Match"]
[s for s in l if s.istitle()]
輸出:
['This Should Only Match']
嘗試使用以下模式使用re.search
進行匹配:
^[A-Z][a-z]*(?: [A-Z][a-z]*)*$
腳本:
list = ["This sentence should Not Match", "This Should Only Match"]
matches = []
for l in list:
x = re.search("^[A-Z][a-z]*(?: [A-Z][a-z]*)*$", l)
if x:
matches.append(l)
print(matches)
這打印:
['This Should Only Match']
我首先支持Chris的解決方案,但這是一種可能的正則表達式方法:
import re
sentences = ["This sentence should Not Match", "This Should Only Match"]
result = [x for x in sentences if re.match(r"^([A-Z][a-z]*\b\s*)+$", x)]
print(result) # => ["This Should Only Match"]
正則表達式僅匹配具有一個或多個單個大寫字母的字符串,后跟0或更多小寫字母,單詞邊界和可選空格。
注意:盡量避免覆蓋內置函數list()
並且總是使正則表達式字符串原始是一個好習慣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.