python - Convert user input strings to raw string literal to construct regular expression -


i know there posts convert string raw string literal, none of them situation.

my problem is:

say, example, want know whether pattern "\section" in text "abcd\sectiondefghi". of course, can this:

import re  motif = r"\\section" txt = r"abcd\sectiondefghi" pattern = re.compile(motif) print pattern.findall(txt) 

that give me want. however, each time want find new pattern in new text, have change code painful. therefore, want write more flexible, (test.py):

import re import sys  motif = sys.argv[1] txt = sys.argv[2] pattern = re.compile(motif) print pattern.findall(txt) 

then, want run in terminal this:

python test.py \\section abcd\sectiondefghi 

however, not work (i hate use \\\\section).

so, there way of converting user input (either terminal or file) python raw string? or there better way of doing regular expression pattern compilation user input?

thank much.

use re.escape() make sure input text treated literal text in regular expression:

pattern = re.compile(re.escape(motif)) 

demo:

>>> import re >>> motif = r"\section" >>> txt = r"abcd\sectiondefghi" >>> pattern = re.compile(re.escape(motif)) >>> txt = r"abcd\sectiondefghi" >>> print pattern.findall(txt) ['\\section'] 

re.escape() escapes non-alphanumerics; adding backslash in front of each such character:

>>> re.escape(motif) '\\\\section' >>> re.escape('\n [hello world!]') '\\\n\\ \\[hello\\ world\\!\\]' 

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -