Capture the text inside square brackets using a regex

前端 未结 3 1613
执念已碎
执念已碎 2021-01-21 02:24

I saw question here: Regex to capture {} which is similar to what I want, but I cannot get it to work.

My data is:



        
3条回答
  •  情歌与酒
    2021-01-21 03:01

    You only have one group in your expression, so you can only ever get that one group. Group 1 is the capturing group, group 0 is the whole matched text; in your expression they are one and the same. Had you omitted the (...) parentheses, you'd only have a group 0.

    If you wanted to get all matches, use re.findall(). This returns a list of matching groups (or group 0, if there are no capturing groups in your expression):

    >>> import re
    >>> re.findall('\[[^\[\]]*\]', '[Honda] Japanese manufacturer [VTEC] Name of electronic lift control')
    ['[Honda]', '[VTEC]']
    

提交回复
热议问题