pandas ValueError: pattern contains no capture groups

后端 未结 3 1370
迷失自我
迷失自我 2020-12-10 13:59

When using regular expression, I get:

import re
string = r\'http://www.example.com/abc.html\'
result = re.search(\'^.*com\', string).group()
<
3条回答
  •  余生分开走
    2020-12-10 14:14

    According to the docs, you need to specify a capture group (i.e., parentheses) for str.extract to, well, extract.

    Series.str.extract(pat, flags=0, expand=True)
    For each subject string in the Series, extract groups from the first match of regular expression pat.

    Each capture group constitutes its own column in the output.

    df.url.str.extract(r'(.*.com)')
    
                            0
    0  http://www.example.com
    1    http://www.hello.com
    

    # If you need named capture groups,
    df.url.str.extract(r'(?P.*.com)')
    
                          URL
    0  http://www.example.com
    1    http://www.hello.com
    

    Or, if you need a Series,

    df.url.str.extract(r'(.*.com)', expand=False)
    
    0    http://www.example.com
    1      http://www.hello.com
    Name: url, dtype: object
    

提交回复
热议问题