53

This code works if I use raw strings only. However, as soon as I add f to r it stops working.

Is there a way to make f-strings work with raw strings for re?

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
1
  • 10
    Why are you using f-strings at all? It doesn't look like you want to do any interpolation. Commented Aug 6, 2017 at 1:57

1 Answer 1

96

The new fstrings in Python interpret brackets in their own way. You can escape brackets you want to see in the output by doubling them:

regex = fr'(\d{{1,2}})/(\d{{1,2}})/(\d{{4}}|\d{{2}})'
3
  • 24
    Apparently raw f-strings are a thing. Weird as heck. Commented Aug 6, 2017 at 1:59
  • 1
    @user2357112 I agree. Regex is complicated enough. I stayed away from mixing them now. I even made smaller regex and matched them separately. It made my life easier. Commented Aug 6, 2017 at 23:42
  • 3
    Still the raw f-string is part of the PEP498 (python.org/dev/peps/pep-0498/#raw-f-strings). Commented Mar 7, 2020 at 10:51

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.