我将大多数用户使用的简单正则表达式格式转换为正确的re python正则表达式字符串的最简单方法是什么?
作为一个例子,我需要转换这个:
string = "*abc+de?"
对此:
string = ".*abc.+de.?"
当然,我可以遍历字符串并按字符构建另一个字符串,但这肯定是一种低效的方法吗?
那些看起来不像你试图翻译的正则表达式,它们看起来更像unix shell globs.Python有一个模块用于执行此操作.它不知道你使用的"+"语法,但我的shell也不知道,我认为语法是非标准的.
>>> import fnmatch >>> fnmatch.fnmatch("fooabcdef", "*abcde?") True >>> help(fnmatch.fnmatch) Help on function fnmatch in module fnmatch: fnmatch(name, pat) Test whether FILENAME matches PATTERN. Patterns are Unix shell style: * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any char not in seq An initial period in FILENAME is not special. Both FILENAME and PATTERN are first case-normalized if the operating system requires it. If you don't want this, use fnmatchcase(FILENAME, PATTERN). >>>