Search code examples
pythonpython-3.xtext-parsing

How do I extract substrings immediately before the nearest punctuation?


From a text file using Python 3.12, how do I extract substrings from lines that have multiple parentheses:

line1: 'group(something)'
line2: 'other(something) and group(something,something,something) and not group(something,something)'

I'm only interested in the 'something' 's from the 'group()' or 'not group()'.

def find_within(search_in, search_for, until):
    return search_in[search_in.find(search_for) + len(search_for) : search_in.find(until)]

group1 = find_within(line1, 'group(', ')')        # extracting group from the first line
group2 = find_within(line2, 'and group(', ')')    # extracting group from the second line
not_group = find_within(line2, 'not group(', ')')    # extracting 'not group' from the second line

This function can handle extraction from lines that have only a single 'group()' like line1 but not the lines with multiple items like line2 (it would return null). I tried replacing the last .find() by .rfind():

def find_within(search_in, search_for, until):
    return search_in[search_in.find(search_for) + len(search_for) : search_in.rfind(until)]

But the output was:

'something,something,something) and not group(something,something'

while I expect:

'something,something,something'

.find() looks for the first occurrence of the parenthesis, so when I'm seeking 'something' from 'group(something)' that is in the middle of the string, .find() looks at the closing parenthesis from a pair ahead of 'group(something)', so returns ''. And .rfind() looks for the last occurrence of the parenthesis so extracts everything until the last parenthesis.

Is there a better way with .find() or do I need regular expressions?


Solution

  • I think the thing that you may be missing is that you can give str.find() a second optional integer argument (str.find(target, offset)) to tell where you want to start the search.

    So in the example below we being with start = 0 for start of string

    if we find the target string we advance start by offset to point to the character just past the '(' character. Then we search from that position forward to find the next ')' character which is our stop position

    then the contents of the parentheses are just a slice from stop to start. In my example I then appended the contents to a list but you could print it out, or whatever you needed

    eventually str.find() will return -1 indicating there are no further matches so we return from the function

    text = "group(a, b, c) and group(d, e, f) and not group(g, h, i)"    
    
    
    def findit(target, text):
        
        """look for target followed by (
           save the text following the ( until the next )
           append that text to results
           when target doesn't match any more return results"""
           
        results = []
        target += '('    #add open parenthesis after target
        offset = len(target)
        
        start = 0
        while True:
            start = text.find(target, start)
            #print(start)
            if start == -1:
                break
            
            start += offset
            stop = text.find(')', start)
            contents = text[start:stop]
            results.append(contents)
            
        return results
    
    print("\ngroup")
    print(findit('group', text))
    
    print("\nand group")
    print(findit('and group', text))
    
    print("\nnot group")
    print(findit('not group', text))
    

    this program will produce this output:

    group
    ['a, b, c', 'd, e, f', 'g, h, i']
    
    and group
    ['d, e, f']
    
    not group
    ['g, h, i']