简体   繁体   中英

Regular expression to escape regular expressions

Yesterday, I needed to add a file path to a regular expression creating a pattern like this:

"some_pattern/%s/more_pattern" % some_path

In the beginning the regular expression did not match, because some_path contained several regex specific symbols like ? or . . As a quick fix I replaced them with [?]{1} and . with \\. .

However, I asked myself if there isn't a more reliable or better way to clean a string from regex specific symbols.

  • Is such functionality supported in the Python Standard library?
  • If not, do you know a regular expression to identify all regex symbols and clean them through a substitute?

Just apply re.escape and you'll be fine.

re.escape(string)

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM