user11229588
user11229588

Reputation:

How do i make regex for final occurence of a string

I want to make a regex of that search for the final occurence of given alphabet in a string.

import re
string = "Hello stackoverflow"
[print(re.sub('o', '*', string))]

i'm expecting "Hello stackoverfl*w" as the result

Upvotes: 1

Views: 53

Answers (3)

GZ0
GZ0

Reputation: 4273

Another solution:

re.sub(r"(.*)o", r"\1*", string)

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521457

We can try using re.sub for a regex option:

string = "Hello stackoverflow"
output = re.sub(r'^(.*)o(.*)$', '\\1*\\2', string)
print(output)

This prints:

Hello stackoverfl*w

Upvotes: 1

mechanical_meat
mechanical_meat

Reputation: 169344

You could reverse the string, do the replacement once, and return the re-reversed string:

re.sub('o','*',string[::-1],1)[::-1]
#                           ^ this means do the replacement only once

Upvotes: 1

Related Questions