0

A basic version of this problem is using an regex to translate something like abc like '%FFddsdE%' into LOWER(abc) like '%ffddsde%'
and the following code works well

import re
text = "abc like '%FFddsdE%'"
print("before: " + text)
text = re.sub('([^ ^\n]+?) ?like ?\'([^ ]+)\'', 
             lambda s: f'LOWER({s.group(1)}) like \'{s.group(2).lower()}\'', 
             text, flags=re.I)
print("after: " + text)


#the output is
#before: abc like '%FFddsdE%'
#after: LOWER(abc) like '%ffddsde%'

However, everything crash down if we want to expand this problem a little bit, to both like and not like

import re

text = "abc not like '%FFddsdE%' and bcd like '%XyZ%'"
print("before: " + text)
text = re.sub('([^ ^\n]+?) ?not like ?\'([^ ]+)\'', 
             lambda s: f'LOWER({s.group(1)}) not like \'{s.group(2).lower()}\'', 
             text, flags=re.I)
text = re.sub('([^ ^\n]+?) ?like ?\'([^ ]+)\'', 
             lambda s: f'LOWER({s.group(1)}) like \'{s.group(2).lower()}\'', 
             text, flags=re.I)
print("after: " + text)

#the output is
#before: abc not like '%FFddsdE%' and bcd like '%XyZ%'
#after: LOWER(abc) LOWER(not) like '%ffddsde%' and LOWER(bcd) like '%xyz%'

It gives LOWER(not) in the output.

I am using python 3 btw. Thanks for any help!

1 Answer 1

3

You could use another group to match like and not like at the same time.

import re
text = "abc not like '%FFddsdE%' and bcd like '%XyZ%'"
print("before: " + text)
text = re.sub('([^ ^\n]+?) ?(like|not like) ?\'([^ ]+)\'',
             lambda s: f'LOWER({s.group(1)}) {s.group(2)} \'{s.group(3).lower()}\'',
             text, flags=re.I)
print("after: " + text)

# before: abc not like '%FFddsdE%' and bcd like '%XyZ%'
# after: LOWER(abc) not like '%ffddsde%' and LOWER(bcd) like '%xyz%'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.