Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RegEx Python: extract substring from string

I have several strings (some values may differ but format is ultimately the same):

"I Suck At Regex: 100.00 WHATIWANT Plz Help: Thank you: 200.00"
"I Suck At Regex: 200.00 WHATIWANT Plz Help: Thank you: 200.00"
"I Suck At Regex: 300.00 ALSOWANT Plz Help: Thank you: 300.00"

I would like to extract the substring ‘WHATIWANT’ from the full string

I tried using [A-Z] to only extract capitalized letters, however, as you can tell, my string has capitalized letters in other positions

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

How about this:

import re

strings = [
    "I Suck At Regex: 100.00 WHATIWANT Plz Help: Thank you: 200.00",
    "I Suck At Regex: 200.00 WHATIWANT Plz Help: Thank you: 200.00",
    "I Suck At Regex: 300.00 ALSOWANT Plz Help: Thank you: 300.00"
]
# match a sequence of letters in the range A-Z with a length of at least 2
p = re.compile(r'\b([A-Z]{2,})\b')

for string in strings:
    print(*p.findall(string))

Output:

WHATIWANT
WHATIWANT
ALSOWANT
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading