35

如果我只使用原始字符串,但只要将 f 添加到 r,此代码就可以工作。它停止工作。有没有办法让 f 字符串与原始字符串一起工作?

import re

lines = '''

    04/20/2009; 04/20/09; 4/20/09; 4/3/09
    Mar-20-2009; Mar 20, 2009; March 20, 2009; Mar. 20, 2009; Mar 20 2009;
    20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009
    Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009
    Feb 2009; Sep 2009; Oct 2010
    6/2008; 12/2009
    2009; 2010

'''
rmonth = 'a'
regex = fr'(\d{1,2})/(\d{1,2})/(\d{4}|\d{2})'
date_found = re.findall(regex, lines)

date_found
4

1 回答 1

60

Python 中的新 fstrings 以自己的方式解释括号。您可以通过将它们加倍来转义要在输出中看到的括号:

regex = fr'(\d{{1,2}})/(\d{{1,2}})/(\d{{4}}|\d{{2}})'
于 2017-08-06T01:53:36.567 回答