[英]how to find uppercase and smallCase using regex -re.findall in python
[英]how to use re.findall to find the words that is NOT of all uppercase letters?
例如,我有s="I REALLY don't want to talk about it, not at all!"
我希望re.findall(reg, s)
返回"I" "don't" "want" "to" "talk" "about" "it" "," "not" "at" "all" "!"
到目前為止,我得到reg=r'[^\\w\\s]+|\\w+|\\n'
,它們無法過濾掉"REALLY"
這個詞
謝謝
\\w+
模式匹配1個或多個單詞字符,包括ALLCAPS中的單詞。
請注意, I
,一個代名詞,也是ALLCAPS。 因此,假設您要跳過2個或更多字母的所有ALLCAPS單詞,您可以考慮將當前模式修改為
r'[^\w\s]+|\b(?![A-Z]{2,}\b)\w+|\n'
請參閱正則表達式演示
\\b(?![AZ]{2,}\\b)\\w+
模式匹配
\\b
- 單詞邊界 (?![AZ]{2,}\\b)
- 如果在當前位置的右側,有兩個或更多ASCII大寫字母后跟一個單詞邊界,則匹配失敗的負前瞻 \\w+
- 1個或更多單詞字符(如果你只想匹配字母,請替換為[^\\W\\d_]+
)。 要支持所有Unicode大寫字母,您可以將PyPi正則表達式與r'[^\\w\\s]+|\\b(?!\\p{Lu}{2,}\\b)\\w+|\\n'
模式一起使用,或者使用pLu = '[{}]'.format("".join([chr(i) for i in range(sys.maxunicode) if chr(i).isupper()]))
構建類pLu = '[{}]'.format("".join([chr(i) for i in range(sys.maxunicode) if chr(i).isupper()]))
(Python 3)或者pLu = u'[{}]'.format(u"".join([unichr(i) for i in xrange(sys.maxunicode) if unichr(i).isupper()]))
(Python 2)。 有關unicode大寫單詞,請參閱Python正則表達式 。 注意我建議堅持使用最新的Python版本或最新的PyPi正則表達式模塊。
Brian Kernighan的引用對於正則表達式尤其如此。
每個人都知道調試的難度是首先編寫程序的兩倍。 因此,如果你在編寫它時就像你一樣聰明,你將如何調試它?
因此,如果在單個正則表達式中難以執行某些操作,則可能需要將其拆分為兩個步驟。 首先查找所有單詞,然后過濾掉所有大寫單詞。 更容易理解,更容易測試。
>>> import re
>>> s="I REALLY don't want to talk about it, not at all!"
>>> words = re.findall(r"[\w']+", s)
>>> words = [w for w in words if w.upper() != w]
>>> print(words)
["don't", 'want', 'to', 'talk', 'about', 'it', 'not', 'at', 'all']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.