-5

I have a windows full path which I try to validate using regex. According to this I have to add "\\\\\\\\" but this is not working.
What am I doing wrong?

import re

regex1 = re.compile('downloads\\\\test_dir\\\\sql\\\\my-ee.sql')  
s = "C:\x\xxx\temp\downloads\test_dir\sql\my-ee.sql"  
gg = regex1.match(s)

gg is None.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
user63898
  • 29,839
  • 85
  • 272
  • 514
  • 1
    Your code has a syntax error – wim Jun 22 '21 at 14:11
  • [`match()`](https://docs.python.org/3/library/re.html#re.match) will return smth only if whole string matches pattern, you probably want to use [`search()`](https://docs.python.org/3/library/re.html#re.search). `re.search(re.escape(r"downloads\test_dir\sql\my-ee.sql"), s)` – Olvin Roght Jun 22 '21 at 14:12
  • In this form, `s` should contain ```\\```-s. – tevemadar Jun 22 '21 at 14:12
  • 1
    @OlvinRoght Small correction: not whole string. Only from the beginning. To match the whole string there is [`fullmatch`](https://docs.python.org/3/library/re.html#re.fullmatch) – Tomerikoo Jun 22 '21 at 14:19
  • @Tomerikoo, yes, missed that and it was too late to edit, thanks for mentioning. – Olvin Roght Jun 22 '21 at 14:19

1 Answers1

1

So there are two things:

  1. The assignment of s should be either with escaped back-slashes or as a raw string. I prefer the latter:
s = r"C:\x\xxx\temp\downloads\test_dir\sql\my-ee.sql" 
  1. you should use the search method instead of match to be content with a partial match.

Then, you can use \\\\ in the regular expression, or - as I prefer - a raw string again:

import re

regex1 = re.compile(r'downloads\\test_dir\\sql\\my-ee.sql')  
s = r"C:\x\xxx\temp\downloads\test_dir\sql\my-ee.sql"  
gg = regex1.search(s)
print(gg)
Dr. V
  • 1,747
  • 1
  • 11
  • 14