Python regex - why does end of string ($ and \Z) not work with group expressions?

前端 未结 3 1204
余生分开走
余生分开走 2020-12-09 04:48

In Python 2.6. it seems that markers of the end of string $ and \\Z are not compatible with group expressions. Fo example

import re         


        
3条回答
  •  一个人的身影
    2020-12-09 05:16

    Martijn Pieters' answer is correct. To elaborate a bit, if you use capturing groups

    r"\w+(\s|$)"
    

    you get:

    >>> re.findall("\w+(\s|$)", "green pears")
    [' ', '']
    

    That's because re.findall() returns the captured group (\s|$) values.

    Parentheses () are used for two purposes: character groups and captured groups. To disable captured groups but still act as character groups, use (?:...) syntax:

    >>> re.findall("\w+(?:\s|$)", "green pears")
    ['green ', 'pears']
    

提交回复
热议问题