Regex nested parenthesis in python

前端 未结 4 1965
灰色年华
灰色年华 2021-01-03 03:41

I have something like this:

Othername California (2000) (T) (S) (ok) {state (#2.1)}

Is there a regex code to obtain:

Other         


        
4条回答
  •  灰色年华
    2021-01-03 04:04

    Try this one:

    import re
    
    thestr = 'Othername California (2000) (T) (S) (ok) {state (#2.1)}'
    
    regex = r'''
        ([^(]*)             # match anything but a (
        \                   # a space
        (?:                 # non capturing parentheses
            \([^(]*\)       # parentheses
            \               # a space
        ){3}                # three times
        \(([^(]*)\)         # capture fourth parentheses contents
        \                   # a space
        {                   # opening {
            [^}]*           # anything but }
            \(\#            # opening ( followed by #
                ([^)]*)     # match anything but )
            \)              # closing )
        }                   # closing }
    '''
    
    match = re.match(regex, thestr, re.X)
    
    print match.groups()
    

    Output:

    ('Othername California', 'ok', '2.1')
    

    And here's the compressed version:

    import re
    
    thestr = 'Othername California (2000) (T) (S) (ok) {state (#2.1)}'
    regex = r'([^(]*) (?:\([^(]*\) ){3}\(([^(]*)\) {[^}]*\(\#([^)]*)\)}'
    match = re.match(regex, thestr)
    
    print match.groups()
    

提交回复
热议问题