Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the last letter in a string that is not a specific character using regex?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading