This is a related question but doesn’t specifically have the answer I’m looking for. How to search for the last occurrence of a regular expression in a string in python?
Essentially, say for input "iuasgjjgg", I want to find the rightmost character that is not "j".
So
solution("abcdefghijh") => 10 (because h is at index 10)
solution("hhhjjjhhh") => 8 (because last h is at index 8)
the fact that it is "h" is not important, it’s just important that it’s not "j"
I think it has something to do with re.search and negative lookaheads but I’m having trouble putting everything together.
edit: also I know that this is probably possible using a naive approach but I’m looking for a regex solution.
>Solution :
One approach would be to rstrip the letter j, and then take the final remaining character:
inp = ["abcdefghijh", "hhhjjjhhh"]
last = [x.rstrip('j')[-1] for x in inp]
print(last) # ['h', 'h']
If instead you want the final index of the above characters, just take the length:
inp = ["abcdefghijh", "hhhjjjhhh"]
last = [len(x.rstrip('j')) - 1 for x in inp]
print(last) # [10, 8]