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}')
如果对你有所帮助,请帮忙点赞+关注+分享