Extracting words between delimiters [] in python

后端 未结 3 976
野性不改
野性不改 2021-02-04 15:02

From the below string, I want to extract the words between delimters [ ] like \'Service Current\',\'Service\',\'9991\',\'1.22\':

str=\'         


        
相关标签:
3条回答
  • 2021-02-04 15:47
    re.findall(r'\[([^\]]*)\]', str)
    
    0 讨论(0)
  • 2021-02-04 16:02

    First, avoid using str as a variable name. str already has a meaning in Python and by defining it to be something else you will confuse people.

    Having said that you can use the following regular expression:

    >>> import re
    >>> print re.findall(r'\[([^]]*)\]', s)
    ['Service Current', 'Service', '9991', '1.22']
    

    This works as follows:

    \[   match a literal [
    (    start a capturing group
    [^]] match anything except a closing ]
    *    zero or more of the previous
    )    close the capturing group
    \]   match a literal ]
    

    An alternative regular expression is:

    r'\[(.*?)\]'
    

    This works by using a non-greedy match instead of matching anything except ].

    0 讨论(0)
  • 2021-02-04 16:05

    you can use regex

    import re
    s = re.findall('\[(.*?)\]', str)
    
    0 讨论(0)
提交回复
热议问题