Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I use f-string with regex in Python

This code works if I use raw strings only but 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 
like image 824
Jeremy Chen Avatar asked Aug 06 '17 01:08

Jeremy Chen


People also ask

Can you use F string with regex Python?

... in which we look at one or two ways to make life easier when working with Python regular expressions. tl;dr: You can compose verbose regular expressions using f‍-‍strings. For comparison, the same pattern without f‍-‍strings (click to expand).

What does F {} mean in Python?

Also called “formatted string literals,” f-strings are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values.

How do you align an F string in Python?

To right align a string, we use the “:>n” symbol inside the placeholder.


1 Answers

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}})' 
like image 193
Blckknght Avatar answered Sep 28 '22 04:09

Blckknght