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?

1

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']

1

You can use a pattern to find the expected outputs:

b(group)s*(([^)]+))|s*(bands+group)(([^)]+))|s*(bands+nots+group)(([^)]+))|s*b(other)(([^)]+))

Code:

import re


def _find(p, s):
    return re.findall(p, s)


p = r'b(group)s*(([^)]+))|s*(bands+group)(([^)]+))|s*(bands+nots+group)(([^)]+))|s*b(other)(([^)]+))'
s = """
line1: 'group(something)'
line2: 'other(something) and group(something,something,something) and not group(something,something)'
I'
"""
print(_find(p, s))


Prints

[('group', 'something', '', '', '', '', '', ''), ('', '', '', '', '', '', 'other', 'something'), ('', '', 'and group', 'something,something,something', '', '', '', ''), ('', '', '', '', 'and not group', 'something,something', '', '')]


Notes

  • There are 8 capture groups: four groups are the keys and four groups are the values.
  • (([^)]+)): These four groups are the values.

Edit

You can use a simple pattern and get all the keys and values, and then proceed with your text processing tasks:

import re


def _find(p, s, as_dict=False):
    matches = re.findall(p, s)
    if as_dict:
        return {m[0].strip(): m[1] for m in matches}
    return matches


p = r"s*([^(']+)s*(([^)]+))"
s = """
line1: 'group(something)'
line2: 'other(something) and group(something,something,something) and not group(something,something)'
I'
"""

print(_find(p, s))

print(_find(p, s, as_dict=True))

Prints

[('group', 'something'), ('other', 'something'), ('and group', 'something,something,something'), ('and not group', 'something,something')]
{'group': 'something', 'other': 'something', 'and group': 'something,something,something', 'and not group': 'something,something'}

Details

The second pattern is pretty simple:

  • ([^(']+): capture group 1 finds the keys.
  • s*(([^)]+)): capture group 2 finds the values.
  • [^(']+: means all the chars are allowed, except (i.e., ^) these two [('], and then one or more times (i.e., +).
  • ([^)]+): means all chars are allowed, except (i.e., ^) one char, that is the one, ), in the character class (i.e., []).

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật