How to remove end of substring using regex?

Member

by orpha , in category: Third Party Scripts , 12 days ago

How to remove end of substring using regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 11 days ago

@orpha 

To remove the end of a substring using regex, you can use the regex pattern to match the substring you want to remove and then replace it with an empty string.


For example, if you have the following string:

1
text = "Hello, world! I am a string. Goodbye, world!"


and you want to remove the substring "Goodbye, world!", you can use the re.sub() function in Python to achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import re

text = "Hello, world! I am a string. Goodbye, world!"

# Define the regex pattern to match the substring you want to remove
pattern = r'Goodbye, world!$'

# Replace the matching substring with an empty string
new_text = re.sub(pattern, '', text)

print(new_text)


This will output:

1
Hello, world! I am a string.


In this example, the regex pattern r'Goodbye, world!$' matches the substring "Goodbye, world!" at the end of the string, and the re.sub() function replaces it with an empty string, effectively removing it from the original string.