Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regext to match capitalized word, and the surrounding +- 4 words

Tags:

python

regex

I have a bunch of documents and I'm interested in finding mentions of clinical trials. These are always denoted by the letters being in all caps (e.g. ASPIRE). I want to match any word in all caps, greater than three letters. I also want the surrounding +- 4 words for context.

Below is what I currently have. It kind of works, but fails the test below.

import re
pattern = '((?:\w*\s*){,4})\s*([A-Z]{4,})\s*((?:\s*\w*){,4})'
line = r"Lorem IPSUM is simply DUMMY text of the printing and typesetting INDUSTRY."
re.findall(pattern, line)
like image 955
Chris Daly Avatar asked Mar 07 '23 07:03

Chris Daly


2 Answers

You may use this code in python that does it in 2 steps. First we split input by 4+ letter capital words and then we find upto 4 words on either side of match.

import re

str = 'Lorem IPSUM is simply DUMMY text of the printing and typesetting INDUSTRY'

re1 = r'\b([A-Z]{4,})\b'
re2 = r'(?:\s*\w+\b){,4}'

arr = re.split(re1, str)

result = []

for i in range(len(arr)):
    if i % 2:
        result.append( (re.search(re2, arr[i-1]).group(), arr[i], re.search(re2, arr[i+1]).group()) )


print result

Code Demo

Output:

[('Lorem', 'IPSUM', ' is simply'), (' is simply', 'DUMMY', ' text of the printing'), (' text of the printing', 'INDUSTRY', '')]
like image 110
anubhava Avatar answered Mar 10 '23 10:03

anubhava


Would the following regex works for you?

(\b\w+\b\W*){,4}[A-Z]{3,}\W*(\b\w+\b\W*){,4}

Tested here: https://regex101.com/r/nTzLue/1/

like image 27
Allan Avatar answered Mar 10 '23 11:03

Allan