How to split a string by commas positioned outside of parenthesis?

前端 未结 10 2079
南方客
南方客 2020-11-27 19:36

I got a string of such format:

\"Wilbur Smith (Billy, son of John), Eddie Murphy (John), Elvis Presley, Jane Doe (Jane Doe)\"

so basicly i

10条回答
  •  醉梦人生
    2020-11-27 19:55

    My answer will not use regex.

    I think simple character scanner with state "in_actor_name" should work. Remember then state "in_actor_name" is terminated either by ')' or by comma in this state.

    My try:

    s = 'Wilbur Smith (Billy, son of John), Eddie Murphy (John), Elvis Presley, Jane Doe (Jane Doe)'
    
    in_actor_name = 1
    role = ''
    name = ''
    for c in s:
        if c == ')' or (c == ',' and in_actor_name):
            in_actor_name = 1
            name = name.strip()
            if name:
                print "%s: %s" % (name, role)
            name = ''
            role = ''
        elif c == '(':
            in_actor_name = 0
        else:
            if in_actor_name:
                name += c
            else:
                role += c
    if name:
        print "%s: %s" % (name, role)
    

    Output:

    Wilbur Smith: Billy, son of John
    Eddie Murphy: John
    Elvis Presley: 
    Jane Doe: Jane Doe
    

提交回复
热议问题