How to use python and SQL to delete the combination of numbers and letters at the end but keep the numbers in other place?

Question:

I need to do a regex using python and SQL respectively.

If I have 3 strings like:

aaa bbb 1234 cc d e ff fji1223 345
aaa bbb feij sdkj 434343 458iui3 48
aaa bbb 1234 fjie skfj

The above are three strings. I want to delete the combinations of numbers and letters, or just numbers at the end. But at the same time, still keep the numbers in the middle. So the strings should turn to:

aaa bbb 1234 cc d e ff
aaa bbb feij sdkj
aaa bbb 1234 fjie skfj

Could anyone plz help me out here?

Asked By: Feng Chen

||

Answers:

We can try a regex replacement here in multiline mode:

inp = """aaa bbb 1234 cc d e ff fji1223 345
aaa bbb feij sdkj 434343 458iui3 48
aaa bbb 1234 fjie skfj"""

output = re.sub(r'(?:s+[a-z0-9]*d[a-z0-9]*)+$', '', inp, flags=re.M)
print(output)

This prints:

aaa bbb 1234 cc d e ff
aaa bbb feij sdkj
aaa bbb 1234 fjie skfj

The regex pattern used above matches any word containing at least one digit. The full pattern matches any sequence of such words at the end of each line.

Answered By: Tim Biegeleisen