1.問題場景描述:
????????在sql語句中經常會有查詢條件是:查找多個訂單簽訂日期范圍的數據,但具體的日期范圍是不確定,我們如何來查找定位
例如:查詢條件語句的部分如下圖:
目標是:
? ? ? ? 1)定位字符串:t_contract_order.sign_date
? ? ? ? 2)最終得到結果:
解決問題思路:
? ? ? ? 1)定位要找的字符串起始位置和截止位置
? ? ? ? ? ? ? ? 起始位置的定位:? ??
#--------定位字符串出現的位置
pattern = "t_contract_order.sign_date"
# 使用 re.finditer 查找所有出現的位置
positions = [match.start() for match in re.finditer(pattern, teststr)]
? ? ? ? ? ? ? ? 結束位置的查找技巧是找到第二次出現單引號的位置,使用函數
def find_char_second_occurrence(s, start, char):first_index = s.find(char, start)if first_index == -1:return -1second_index = s.find(char, first_index + 1)return second_index if second_index != -1 else first_index
? ? ? ? 2)去除相關內容,保持sql其他內容的正確性和完整性
for tmpstr in tmpstrs:print(tmpstr)tstr=' and '+tmpstrprint(tstr)teststr=teststr.replace(tstr,'')tstr = ' or ' + tmpstrteststr = teststr.replace(tstr, '')tstr = tmpstr +' and 'teststr = teststr.replace(tstr, '')tstr = tmpstr + ' or 'teststr = teststr.replace(tstr, '')tstr = tmpstrteststr = teststr.replace(tstr, '')print(f'sql={teststr}')
最后將完整代碼提供給大家:
import re
def find_char_second_occurrence(s, start, char):first_index = s.find(char, start)if first_index == -1:return -1second_index = s.find(char, first_index + 1)return second_index if second_index != -1 else first_index# sql查詢語句測試使用
teststr = "where t_contract_order.sign_date<='2019-01-01 00:00:00'" \" and a=b or t_contract_order.sign_date>='2024-01-01 00:00:00'" \" and t_contract_order.sign_date<='2024-12-31 23:59:59'" \" or c=d or t_contract_order.sign_date>='2025-02-28 23:59:59'"#--------定位字符串出現的位置
pattern = "t_contract_order.sign_date"
# 使用 re.finditer 查找所有出現的位置
positions = [match.start() for match in re.finditer(pattern, teststr)]
print(f'字符串{pattern}出現的位置{positions}')
character = "'"
tmpstrs=[]
for position in positions:second_occurrence = find_char_second_occurrence(teststr, position, character)tmpstrs.append(teststr[position:second_occurrence+1])print(position,second_occurrence,teststr[position:second_occurrence+1])
for tmpstr in tmpstrs:print(tmpstr)tstr=' and '+tmpstrprint(tstr)teststr=teststr.replace(tstr,'')tstr = ' or ' + tmpstrteststr = teststr.replace(tstr, '')tstr = tmpstr +' and 'teststr = teststr.replace(tstr, '')tstr = tmpstr + ' or 'teststr = teststr.replace(tstr, '')tstr = tmpstrteststr = teststr.replace(tstr, '')print(f'sql={teststr}')
如果對你有所幫助,請幫忙點贊+關注+分享