开发者

python+postgresql: Convert string literal to regex

开发者 https://www.devze.com 2023-02-19 08:16 出处:网络
I want to execute a query where I match a column name using a regex to my variable, s. s is a string literal and may contain things like ?, *, ., etc. I want to convert s so that ? turns into .{0,3},

I want to execute a query where I match a column name using a regex to my variable, s. s is a string literal and may contain things like ?, *, ., etc. I want to convert s so that ? turns into .{0,3}, so that all of its remaining regex symbols remain literals, and then add .* to the end. examples:

Hi -> Hi.*
Fo?ar -> Fo.{0,3}ar.*
F.a*rx -> F\.a\*rx.*
F.a?*rx -> F\.a.{0,3}\*rx

What's the best way to do this? Mostly I'm unsure how to quote a string literal so the regex symbols 开发者_运维技巧aren't interpreted as regex symbols (e.g. . -> \.).


print '.{0,3}'.join(re.escape(part) for part in s.split('?')) + '.*'


Use the re.escape(string) method.

Which states:

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.

Check out the re module page.

0

精彩评论

暂无评论...
验证码 换一张
取 消