How to remove end of substring using regex?

Member

by orpha , in category: Third Party Scripts , 5 months ago

How to remove end of substring using regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 5 months 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.

Related Threads:

How to remove only words that end with period with regex?
How to replace a substring with a regex pattern using regex in python?
How to remove . (dot) from email before @ using regex?
How to extract a substring of a url with regex?
How to remove part of file name using a regex expression?
How to remove duplicate arithmetic operators using regex?