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}})'
Answer from Blckknght on Stack OverflowHello all, this be my code:
zipCode = "AA 45522"
myPat1 = "(\d{1,9})([^,]+?)AA 45522" # the pattern i want
# now interpolating variable name into the regex pattern
myPat2 = f"(\d{1,9})([^,]+?){zipCode}"
myPat3 = rf"(\d{1,9})([^,]+?){zipCode}" #trying raw
myPat4 = "(\d{1,9})([^,]+?)"+zipCode
# Results I see in debugger:
myPat1 = '(\\d{1,9})([^,]+?)AA 45522' # correct
myPat4 = '(\\d{1,9})([^,]+?)AA 45522' # correct
myPat2 = '(\\d(1, 9))([^,]+?)AA 45522' # faulty
myPat3 = '(\\d(1, 9))([^,]+?)AA 45522' # faulty
myPat2 & myPat3 are adding a space between (1, & 9) which is resulting into creation of faulty pattern (which in turn fails to find pattern in my rawString). So why does using f-string inside regex pattern fudge things up? I recall facing same problem few weeks back.
Finally I have to use myPat4 style of coding to make it work, but I love f-strings and want to find a proper solution to using f-strings inside regex pattern. Thanks.
Videos
[SOLVED]
Hello everyone,
Very simple question, that I couldn't find the answer of.
Basically, I want to use an f-string in my regex, but brackets are used to define a specific number of instances. I.E.
>>> import re
>>> word='AAA'
>>> re.search('[A-Z]{3}',word)
<re.Match object; span=(0, 3), match='AAA'>
>>> pre_defined_variable='A'
>>> re.search(f'{pre_defined_variable}{3}',word)
>>> re.search(f'{pre_defined_variable}',word)
<re.Match object; span=(0, 1), match='A'>So you can see above, using f-strings does work, but only if you are not using the regex brackets for "how many instances of". How do I use both?
It's not the f-string that's the problem. The r prefix on a string doesn't mean "regex", it means "raw" - i.e. backslashes are taken literally. For regex, use the re module. Here's an example using Pattern.match:
import re
regex = fr'2019-11-10T{test_time}:\d{{2}}'
pattern = re.compile(regex)
for child in root:
if pattern.match(child.attrib['startDateTime']):
print('Found')
You can put a regexp in an f-string, but you need to use the re module to match with it, not ==.
if re.match(fr'2019-11-10T{test_time}:\d{{2}}', child.attrib['startDateTime']):
print('Found')
today, while answering a question on stackoverflow, another user suggested I use a raw string when generating a regex pattern dynamically. I was using f-strings to build the regex like this.
words = ['foo', 'bar', 'baz']
pat = f"\\b({ '|'.join(words)})\\b"
# pat -> '\\b(foo|bar|baz)\\b'but following the kind user's comment, I tried out the following and it works!
words = ['foo', 'bar', 'baz']
pat = rf"\b({'|'.join(words)})\b"
# pat -> '\\b(foo|bar|baz)\\b'TIL something new & something I'll probably be using in many places.