SQLクエリの入力とリストとしてクエリ結果文字列があります。
どのSQLクエリの結果文字列を出力できるかを確認したいと思います。
例えば :
結果文字列
val = 15.1a
クエリのリスト:
["select * from table where val like "15%",
"select * from table where val in ("15.1a", "15.1b"),
"select * from table where val = "15.1",
"select * from table where val != "15",
"select * from table where val = "18",
]
したがって、ここでは、0,1,3のインデックスクエリを実行すると、結果の文字列が表示されることがわかります。
Pythonでそれを行う方法はありますか?私はその仕事をすることができるいくつかの正規表現を探しているのではなく、そのためにSQLエンジンを使いたくありません。
ありがとう
興味深い質問:
import re
query_list = [
"select * from table where val like '15.1%'",
"select * from table where val in ('15.1a', '15.1b')",
"select * from table where val = '15.1'",
"select * from table where val != '15'",
"select * from table where val = '18'",
]
# pattern to capture only the value used in comparing
# val like '%some%value' will return str %some%value without quotes
operations = {
'like': r".*?(?:val\slike\s+')(.*)(?:'.*)",
'in': r".*?(?:val\s+in\s+\()(.*)(?:\).*)",
'=': r".*?(?:val\s+=\s+')(.*)(?:'.*)",
'!=': r".*?(?:val\s+\!=\s+')(.*)(?:'.*)",
}
valid_query = []
val = '15.1a'
for query in query_list:
for op, pattern in operations.items():
m = re.match(pattern, query)
if m:
comparing_value = m.groups(0)[0]
if op == 'like':
# here we use regex with non greedy operator
pcomparing_value = r'{}'.format(comparing_value.replace('%', '.*?'))
if re.match(pcomparing_value, val):
valid_query.append(query)
# compare val without quotes must be equal
elif op == '=' and val == comparing_value:
valid_query.append(query)
# compare val without quotes must not be equal
elif op == '!=' and val != comparing_value:
valid_query.append(query)
# for in operator compare val with quotes too
elif op == 'in' and "'{}'".format(val) in comparing_value:
valid_query.append(query)
print(valid_query)
の出力val = '15.1a'
:
["select * from table where val like '15.1%'", "select * from table where val in ('15.1a', '15.1b')", "select * from table where val != '15'"]
の出力val = '15'
は[]
の出力val = '18'
は:
["select * from table where val != '15'", "select * from table where val = '18'"]
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加