python - 正则表达式:如何匹配某些字符所包含的内容?
问题描述
我正在寻找一种使用 python 选择和替换字符串中某个部分的方法re.sub
。
在我的情况下,字符串是
'SELECT * FROM contacts WHERE "id"=%user.id%;'
标志中的内容%
应该是返回数字、字符串或其他的简短可执行代码。
# having these
user = User(id=123)
'SELECT * FROM contacts WHERE "id"=%user.id%;'
# output should be
'SELECT * FROM contacts WHERE "id"=123;'
但是也
# having these
user = User(id=123, name="John Smith")
'''SELECT * FROM contacts WHERE "name"=%user.name.lower().replace(" ", "_")%;'''
# output should be
'''SELECT * FROM contacts WHERE "name"='john_smith';'''
我对正则表达式很陌生,所以我不知道该怎么做。我试过/%\w+/g
了,但这只会匹配%user
,而不是%user.id%
. 我能做些什么?
解决方案
你可以这样做:
re.sub(r'%([^%]*)%', lambda m: str(eval(m.group(1))), your_string)
但我不会推荐它,至少有两个原因:
- 从用户输入执行任意代码是危险的
- 将值作为字符串替换为 SQL 而不正确引用它们也是危险的