tags:

views:

33

answers:

2

I have very simple python script to match some special characters like -,+,-,. But Im not getting expected result while using regex \ to match a single '\' char.

import re
pat = r'[-+*\\]'
text = 'fdkjdfk\sdsdd'
if re.search(pat,text):
   print re.search(pat,text).group()
else:
   print "not found"

On running above code , it prints 'not found' It seems I am doing some mistake here , any help appreciated !!!

+1  A: 

\ is an escape character.

Try escaping it:

text = 'fdkjdfk\\sdsdd' 
Mario Menger
thanks for reply ...Using text = 'fdkjdfk\\sdsdd' and then pat= r'[-+*\\\]' match it right.But does it means in my text I have to use(replace '\') char '\\' everywhere instead of '\'.
aberry
I haven't used Python enough to give a definitive answer to the question in your comment, but the docs http://docs.python.org/release/2.5.2/ref/strings.html explain more about escape sequences.
Mario Menger
A: 

Here was the main program (here I am filtering some simple math operators from text) where I got error 1st time. And Im still getting 'not found' in this example. Here in txt I have used '\' char but it is not getting picked by regex.

import re
pat = r'(\d+\.?\d*)([+*\/\\-](\d+\.?\d*)){1,}=\d+\.?\d*'
txt ='djhdf 4*5+9\3=22 fdf'
if re.search(pat,txt):
        print re.search(pat,txt).group()
else:
        print "not found"

Please check if any1 able to figure down the issue. Thanks for time !!!

aberry
use raw string for the `txt` as well.
SilentGhost
Above code result in printing 'not found'....If I change txt to txt ='djhdf 4*5+9-3=22 fdf', delete '\' then it works fine. Char class [+*\/\\-] not filtering '\'
aberry
it should be: `txt = r'djhdf 4*5+9\3=22 fdf'`
SilentGhost
thanks @SilentGhost . using raw fot txt it worked.But my query is that why I did not need any raw text in 1st example above (that worked fine) and in 2nd case it is Needed.
aberry
it is also needed in your first example, it just happen not to be followed by a number and therefore autoescaped
SilentGhost