File: text_balanced.py

package info (click to toggle)
lapackpp 2024.10.26-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,500 kB
  • sloc: cpp: 80,181; ansic: 27,660; python: 4,838; xml: 182; perl: 99; makefile: 53; sh: 23
file content (20 lines) | stat: -rw-r--r-- 695 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Extracts initial substring delimited by characters start and end.
# Returns substring, excluding delimiters, and remainder. Example:
# (extracted, remainder) = extract_bracketed( "(n*(n+1)) other", '(', ')' )
# extracted = "n*(n+1)"
# remainder = " other"
# see https://stackoverflow.com/questions/1651487/python-parsing-bracketed-blocks
def extract_bracketed( txt, start, end ):
    if (txt[0] != start):
        return (None, txt)
    cnt = 0
    for i in range( 0, len( txt )):
        if (txt[i] == start):
            cnt += 1
        elif (txt[i] == end):
            cnt -= 1
        if (cnt == 0):
            return (txt[1:i], txt[i+1:])
    # unbalanced
    return (None, txt)
# end