3

I have an if statement in a script to see if a directory given via argparse is a UNC path. But does not end with a trailing slash.

import re

#dest is set by argparse. but for this purpose i'll set it manually.
#originally i was escaping each \ in dest. But I found that argparse left them alone.
dest = '\\server-name\folder\subfolder'

if re.match ('^\\+[\w\W]+', dest ) and not re.match( '^\\+[\w\W]+\\$', dest):
    dest = dest + '\\'

I've been playing with this in ipython. The first statement is failing to match. I used the RxToolkit in Komodo IDE, it shows the regex as matching. I tried this webtool: http://www.pythonregex.com/ it matches as well. Any ideas?

2 Answers 2

5

You are passing this to the re:

^\+[\w\W]+

Because \\ means \. What you need to do is to raw your regex strings, by using r:

if re.match(r'^\\+[\w\W]+', dest ) and not re.match(r'^\\+[\w\W]+\\$', dest):
            ^                                       ^
Sign up to request clarification or add additional context in comments.

Comments

4

The string "\\" represent a single backslash \.

>>> print('\\')
\

You need to escape \ or should use raw string literal to represent two backslashes.

>>> print('\\\\')
\\
>>> print(r'\\')
\\

BTW, re.match check for match at the beginning of the string; you can omit the leading ^.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.