0

i have this simple string :

ss = os.path.normpath('sql/foo/my-script.sql')
regex1 = re.compile(r'{}'.format(ss))

getting :

Traceback (most recent call last):
  File "c:\Python36-64\Lib\sre_parse.py", line 855, in parse
    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
  File "c:\Python36-64\Lib\sre_parse.py", line 416, in _parse_sub
    not nested and not items))
  File "c:\Python36-64\Lib\sre_parse.py", line 502, in _parse
    code = _escape(source, this, state)
  File "c:\Python36-64\Lib\sre_parse.py", line 401, in _escape
    raise source.error("bad escape %s" % escape, len(escape))
sre_constants.error: bad escape \c at position 17

UPDATE here is the full example with the re.escape the result is None

sss = os.path.normpath('sql/foo/my-script.sql')
    xx = r"C:\xxx\xxxx\temp\downloads\xxx\sql\foo\my-script.sql"
    regex22 = re.compile(r'{}'.format(re.escape(sss)))
    gg1 = regex2.search(xx)
user63898
  • 29,839
  • 85
  • 272
  • 514
  • Sure, you need to escape the literal pattern with `re.escape`. `regex1 = re.compile(r'{}'.format(re.escape(ss)))`. You can't just take any string and compile a regex object with this pattern, as it must be a valid regex pattern. – Wiktor Stribiżew Jun 22 '21 at 18:01
  • @WiktorStribiżew i updated the question the problem is when i do : re.search() the reg fail – user63898 Jun 22 '21 at 18:16
  • The escape is breaking more complex regexp as it escape the dot and "(" ")" – user63898 Jun 22 '21 at 18:32
  • What is breaking what? `regex2` is not defined. `regex22.search(xx)` finds a match. See [this Python demo](https://ideone.com/GMTWaT), there is a match. – Wiktor Stribiżew Jun 22 '21 at 19:50

0 Answers0