DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Python (http://www.daniweb.com/forums/forum114.html)
-   -   Regex for re.match not working as expected. (http://www.daniweb.com/forums/thread150279.html)

unkwntech Oct 9th, 2008 11:02 pm
Regex for re.match not working as expected.
 
I have the following code:
import re
string = 'c:\test.doc'
if re.match(r":\\[0-9a-z]", string):
      ##r":\\[0-9a-z]" should match ':\t'
      print 'true'
else:
      print 'false'
the problem I am having is that this is always evaluating to false.

solsteel Oct 9th, 2008 11:23 pm
Re: Regex for re.match not working as expected.
 
The substring "\t" in string is evaluated as a tab character. The re method match only matches at the beginning of a string. Try this:
import re
s = r'c:\test.doc'
m = re.search(r":(\\[0-9a-z])", s)
if m:
      print m.group(1)
else:
      print m

unkwntech Oct 9th, 2008 11:30 pm
Re: Regex for re.match not working as expected.
 
Ok, I'm not used to that yet, in PHP if I encased the string in ' it would have not evaluated the \t, or any other special character.

Thanks.

jlm699 Oct 10th, 2008 1:41 am
Re: Regex for re.match not working as expected.
 
you could just as easily do
s = 'c:\\test.doc'

solsteel Oct 10th, 2008 1:50 am
Re: Regex for re.match not working as expected.
 
If the file name is a variable returned from some source:
>>> s = "c:\test.doc"
>>> s1 = repr(s).strip("'")
>>> s1
'c:\\test.doc'
>>>


All times are GMT -4. The time now is 11:38 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC