Python regex split without empty string

后端 未结 5 1521
栀梦
栀梦 2020-12-03 09:54

I have the following file names that exhibit this pattern:

000014_L_20111007T084734-20111008T023142.txt
000014_U_20111007T084734-20111008T023142.txt
...
         


        
5条回答
  •  误落风尘
    2020-12-03 10:33

    Don't use re.split(), use the groups() method of regex Match/SRE_Match objects.

    >>> f = '000014_L_20111007T084734-20111008T023142.txt'
    >>> time_info = re.search(r'[LU]_(\w+)-(\w+)\.', f).groups()
    >>> time_info
    ('20111007T084734', '20111008T023142')
    

    You can even name the capturing groups and retrieve them in a dict, though you use groupdict() rather than groups() for that. (The regex pattern for such a case would be something like r'[LU]_(?P\w+)-(?P\w+)\.')

提交回复
热议问题