Discussion:
ignore special characters in python regex
(too old to reply)
Astan Chee
2009-07-21 05:02:57 UTC
Permalink
Hi,
I'm reading text from a file (per line) and I want to do a regex using
these lines but I want the regex to ignore any special characters and
treat them like normal strings.
Is there a regex function that can do this?
Here is what I have so far:
fp = open('file.txt','r')
notes = fp.readlines()
fp.close()
strin = "this is what I want"
for note in notes:
if re.search(r""+ str(note) + "",strin):
print "Found " + str(note) + " in " + strin

Thanks for any help
Frank Buss
2009-07-21 05:18:01 UTC
Permalink
Post by Astan Chee
I'm reading text from a file (per line) and I want to do a regex using
these lines but I want the regex to ignore any special characters and
treat them like normal strings.
Is there a regex function that can do this?
Maybe re.escape helps?
--
Frank Buss, ***@frank-buss.de
http://www.frank-buss.de, http://www.it4-systems.de
John Machin
2009-07-21 06:01:38 UTC
Permalink
Post by Astan Chee
Hi,
I'm reading text from a file (per line) and I want to do a regex using
these lines but I want the regex to ignore any special characters and
treat them like normal strings.
Is there a regex function that can do this?
It would help if you were to say

(1) what "ignore ... characters" means -- pretend they don't exist?
(2) what are "special chararacters" -- non-alphanumeric?
(3) what "treat them like normal strings" means
(4) how you expect these special characters to be (a) ignored and (b)
"treated like normal strings" /at the same time/.

Cheers,
John
Gabriel Genellina
2009-07-21 09:56:33 UTC
Permalink
Post by Astan Chee
I'm reading text from a file (per line) and I want to do a regex using
these lines but I want the regex to ignore any special characters and
treat them like normal strings.
Is there a regex function that can do this?
fp = open('file.txt','r')
notes = fp.readlines()
fp.close()
strin = "this is what I want"
print "Found " + str(note) + " in " + strin
You don't even need a regex for that.

py> "fragil" in "supercalifragilisticexpialidocious"
True

Note that: r""+ str(note) + ""
is the same as: str(note)
which in turn is the same as: note

Remember that each line keeps its '\n' final!

for note in notes:
if note.rstrip('\n') in strin:
print "Found %s in %s" % (note, strin)
--
Gabriel Genellina
Loading...