Regular expression for ALL CAPS at the beginning of a text block in Python

Viewed 51

I'm having difficulty in putting together a regex pattern that separates out all caps words in the beginning of a paragraph with the rest of the paragraph.

    text_example = 
      """HERE IS SOME TEXT, AND HERE IS SOME MORE; AND ANOTHER START. There is a lot of text 
      that I am also interested in extracting and that will have a variety of Information, 
      symbols @#$^*&^ and even amounts such as $4,123,156 to be included as well."""

Suppose I have the above text. I want to capture HERE IS SOME TEXT, AND HERE IS SOME MORE; AND ANOTHER START. - a pattern of all caps words and punctuation at the start of a passage - and the remaining There is a lot of text that I am also interested in... - that is text with symbols, numbers, and some capital letters at the start of new sentences or for names etc.

I have the following pattern I've been working on and it isn't quite right

pattern = re.compile(r"([A-Z]+\s?[A-Z]+[^a-z0-9])(.*)")
passage_start = re.search(pattern, text).group(1)
passage_remaining = re.search(pattern, text).group(2)

print(passage_start)
print()
print(passage_remaining)

When running this, I get:

HERE IS

SOME TEXT, AND HERE IS SOME MORE; AND ANOTHER START. There is a lot of text that I 
am also interested in extracting and that will have a variety of Information, symbols 
@#$^*&^ and even amounts such as $4,123,156 to be included as well.

Would appreciate some help! Thanks

2 Answers

If you can guarantee that there will be a space between the caps and non caps part, you could use ^([A-Z\.,; ]*) (.*) with the re.DOTALL flag set.

If the space between the parts CANT be guaranteed, you can use ^([A-Z\.,; ]*) ?(.*) (again with the re.DOTALL flag), but you need to then move the last character of the first group to the second group.

You can use

^([^a-z]+)\b(.*)

See the regex demo. Details:

  • ^ - start of a string
  • ([^a-z]+) - Group 1: any zero or more chars other than lowercase ASCII letters
  • \b - a word boundary
  • (.*) - Group 2: any zero or more chars, as many as possible.

See a Python demo:

import re
rx = r"^([^a-z]+)\b(.*)"
text = "HERE IS SOME TEXT, AND HERE IS SOME MORE; AND ANOTHER START. There is a lot of text that I am also interested in extracting and that will have a variety of Information, symbols @#$^*&^ and even amounts such as $4,123,156 to be included as well."
m = re.search(rx, text, re.DOTALL)
if m:
    print(m.group(1)) # HERE IS SOME TEXT, AND HERE IS SOME MORE; AND ANOTHER START. 
    print(m.group(2)) # There is a lot of text that I am also interested in extracting and that will have a variety of Information, symbols @#$^*&^ and even amounts such as $4,123,156 to be included as well.
Related