Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Regex re.sub to remove everything before and including a specified word

Tags:

python

regex

I've got a string, which looks like "Blah blah blah, Updated: Aug. 23, 2012", from which I want to use Regex to extract just the date Aug. 23, 2012. I found an article in the stacks which has something similar: regex to remove all text before a character, but that's not working either when I tried

date_div = "Blah blah blah, Updated: Aug. 23, 2012"
extracted_date = re.sub('^[^Updated]*',"", date_div)

How can I remove everything up to and including Updated, so that only Aug. 23, 2012is left over?

Thanks!

like image 838
maudulus Avatar asked Jul 30 '14 19:07

maudulus


People also ask

What does re SUB do regex?

The re. sub() function is used to replace occurrences of a particular sub-string with another sub-string. This function takes as input the following: The sub-string to replace.

How do I remove a specific character from a string in regex?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")

What is the use of RE sub in Python?

sub() function belongs to the Regular Expressions ( re ) module in Python. It returns a string where all matching occurrences of the specified pattern are replaced by the replace string. To use this function, we need to import the re module first.

What does re match () return?

This function only checks for a match at the beginning of the string. This means that re. match() will return the match found in the first line of the string, but not those found in any other line, in which case it will return null .


1 Answers

In this case, you can do it withot regex, e.g:

>>> date_div = "Blah blah blah, Updated: Aug. 23, 2012"
>>> date_div.split('Updated: ')
['Blah blah blah, ', 'Aug. 23, 2012']
>>> date_div.split('Updated: ')[-1]
'Aug. 23, 2012'
like image 90
mkriheli Avatar answered Oct 05 '22 09:10

mkriheli