split_into_parameters.py

#!/usr/bin/python3
# ===================================================================
# split string into parameters using regular expressions
# comma used as a separator not a terminator
# parameters are striped of start and end whitespace
# ===================================================================

import user_interface as ui
import re

# -------------------------------------------------------------------
# ---- remove prefix from string
# -------------------------------------------------------------------

def remove_prefix(s,prefix):
    return s[len(prefix):]

# -------------------------------------------------------------------
# ---- split string into parameters
# ---- (comma is a separator not a tereminator)
# -------------------------------------------------------------------

def split_into_parameters(s):

    a = []                         # parameter array

    while True:

        m = re.search('^.*?,',s)   # parameter match?

        if m:                      # match?

            p = m.group()          # prefix

            a.append(p.replace(',','').strip())

            s = remove_prefix(s,p)

        else:                      # no match

            a.append(s.strip())

            break

    return a

# -------------------------------------------------------------------
# ----- main
# -------------------------------------------------------------------

if __name__ == '__main__':

    if not ui.running_python3():
        print()
        print('Must run Python3 - exit program')
        print()
        sys.exit()

    while True:                # loop

        ui.clear_screen()
        print()
        s = ui.get_user_input('Enter param string: ')
        if not s:              # empty string?
            break

        print()

        a = split_into_parameters(s)

        print(f'param list length = {len(a)}')

        for x in a:
            print(f'param: "{x}"')

        ui.pause()