Say, for example, I want to know whether the pattern "\section" is in the text "abcd\sectiondefghi". Of course, I can do this:
import re
motif = r"\\section"
txt = r"abcd\sectiondefghi"
pattern = re.compile(motif)
print pattern.findall(txt)
That will give me what I want. However, each time I want to find a new pattern in a new text, I have to change the code which is painful. Therefore, I want to write something more flexible, like this (test.py
):
import re
import sys
motif = sys.argv[1]
txt = sys.argv[2]
pattern = re.compile(motif)
print pattern.findall(txt)
Then, I want to run it in terminal like this:
python test.py \\section abcd\sectiondefghi
However, that will not work (I hate to use \\\\section
).
So, is there any way of converting my user input (either from terminal or from a file) to python raw string? Or is there a better way of doing the regular expression pattern compilation from user input?
Thank you very much.
One way to do this is using an argument parser, like
optparse
orargparse
.Your code would look something like this:
An example of me using it:
Using your example:
So just to be clear, is the thing you search for ("\section" in your example) supposed to be a regular expression or a literal string? If the latter, the
re
module isn't really the right tool for the task; given a search stringneedle
and a target stringhaystack
, you can do:all of which are more efficient than the regexp-based version.
re.escape
is still useful if you need to insert a literal fragment into a larger regexp at runtime, but if you end up doingre.compile(re.escape(needle))
, there are for most cases better tools for the task.EDIT: I'm beginning to suspect that the real issue here is the shell's escaping rules, which has nothing to do with Python or raw strings. That is, if you type:
into a Unix-style shell, the "\section" part is converted to "\section" by the shell, before Python sees it. The simplest way to fix that is to tell the shell to skip unescaping, which you can do by putting the argument inside single quotes:
Compare and contrast:
(explicitly using print on a joined string here to avoid
repr
adding even more confusion...)Use
re.escape()
to make sure input text is treated as literal text in a regular expression:Demo:
re.escape()
escapes all non-alphanumerics; adding a backslash in front of each such a character: