Capturing all consecutive words with spaces with regex in python?
I am trying to match all sequential all words / phrases using regex in Python. Considering the following:
text = "The following words are ALL CAPS. The following word is in CAPS."
The code will return:
ALL CAPS, CAPS
I am currently using:
matches = re.findall('[A-Z\s]+', text, re.DOTALL)
But this returns:
['T', ' ', ' ', ' ', ' ALL CAPS', ' T', ' ', ' ', ' ', ' ', ' CAPS']
I clearly don't need punctuation or "T". I want to return only consecutive words, or one word that only includes the entire uppercase letter.
thank
+3
source to share
4 answers
This does the job:
import re
text = "tHE following words aRe aLL CaPS. ThE following word Is in CAPS."
matches = re.findall(r"(\b(?:[A-Z]+[a-z]?[A-Z]*|[A-Z]*[a-z]?[A-Z]+)\b(?:\s+(?:[A-Z]+[a-z]?[A-Z]*|[A-Z]*[a-z]?[A-Z]+)\b)*)",text)
print matches
Output:
['tHE', 'aLL CaPS', 'ThE', 'Is', 'CAPS']
Explanation:
( : start group 1
\b : word boundary
(?: : start non capture group
[A-Z]+ : 1 or more capitals
[a-z]? : 0 or 1 small letter
[A-Z]* : 0 or more capitals
| : OR
[A-Z]* : 0 or more capitals
[a-z]? : 0 or 1 small letter
[A-Z]+ : 1 or more capitals
) : end group
\b : word boundary
(?: : non capture group
\s+ : 1 or more spaces
(?:[A-Z]+[a-z]?[A-Z]*|[A-Z]*[a-z]?[A-Z]+) : same as above
\b : word boundary
)* : 0 or more time the non capture group
) : end group 1
+1
source to share