0

I'm unable to use the variable p in a regexp:

>>> f="C:\\test\\Win10-20200323080012\\Refactoredtests\\All\\IssueIDcard\\EmptyCard_UserConfirmationPinW\\1E0500E6.png"
>>> p="C:\\test\\Win10-20200323080012\\"

>>> bool(p in f)
True

>>> re.search(rf"^{p}(.*)$",f)
Traceback (most recent call last):
:
re.error: unbalanced parenthesis at position 33
>>> rf"^{p}(.*)$"             
'^C:\\test\\Win10-20200323080012\\(.*)$'

>>> re.search('^C:\\test\\Win10-20200323080012\\(.*)$',f)
Traceback (most recent call last):
:
re.error: unbalanced parenthesis at position 33
# this works using the output of rf"^{p}(.*)$" wrapped in r'':
>>> re.search(r'^C:\\test\\Win10-20200323080012\\(.*)$',f) 
<re.Match object; span=(0, 104), match='C:\\test\\Win10-20200323080012\\Refactoredtests\\'>

repr do not work:

>>> re.search(rf"^{repr(p)}(.*)$",f)                       
>>> rf"^{repr(p)}(.*)$"                                    
"^'C:\\\\test\\\\Win10-20200323080012\\\\'(.*)$"
>>> re.search("^'C:\\\\test\\\\Win10-20200323080012\\\\'(.*)$",f) 

The f and p comes from a program so I'm unable to wrap them with r''

MortenB
  • 2,749
  • 1
  • 31
  • 35
  • Does this answer your question? [Python - regex not escaping parentheses in alphanumeric string with symbols and a variable passed in to method](https://stackoverflow.com/questions/18561361/python-regex-not-escaping-parentheses-in-alphanumeric-string-with-symbols-and) – sophros Mar 23 '20 at 12:57
  • @sophros, no I'm trying to use `rf'{variable}'` which came with python3.6 just to fix stuff like this, but in my example it does not work. Files are all joined from pathlib.Path.parts so there should not be anything hidden there. – MortenB Mar 23 '20 at 13:07
  • 1
    Backslashes (and many other punctuation marks) *mean something* in a regular expression - so your search is applying those meanings, rather than searching for the literal characters you supplied. The `re.escape()` function is supplied to convert such a string into something that will perform a literal match. – jasonharper Mar 23 '20 at 13:30

0 Answers0