How to remove this sentence using python re module

Viewed 39

I want to remove this sentence when I try to get some information. '(adsbygoogle = window.adsbygoogle || []).push({})'

So, I tried to this code using the re module, but I can't help it.

keywords = '(adsbygoogle = window.adsbygoogle || []).push({}) <div class=" pirce.pdf0.92MB  carzip.tistory.com remain)'
cleantext = re.sub('\(', '<', keywords)
cleantext = re.sub('\)', '>', cleantext)
cleantext = re.sub('<ads*[^)]+>', '', cleantext)
cleantext = re.sub('<','(',cleantext)
cleantext = re.sub('>', ')', cleantext)
print(cleantext)

--> result : None

I want 'remain' remain after print(cleantext) but I got the result None. I think re module + grammar run maximum size. how to handle this problem?

thanks first.

I want the words "remain" to remain after print(cleantext)

2 Answers

How consistently is it that you want the last word of this input string? Naively:

result = keywords.split()[-1].strip(")")

If you absolutely must use regex, why not just approach it by removing everything you can:

result = re.sub(".* ", "", keywords).strip(")")

By way of clarification, the .* is greedy. It'll replace everything up until the last space in your input string. That leaves you with remain), the strip at the end cleans it up for you.

-- Edits for comments --

Based on the commentary, it sounds like you just want to drop prefixes. Why not:

prefix = "(adsbygoogle = window.adsbygoogle || []).push({})"
result = keywords.replace(prefix, "")
# ... Extra manipulations here as necessary

For one final regex-based option (if you are certain you have to go this route):

result = re.sub(".*?\}\)", "", keywords)

This last will give you: ' <div class=" pirce.pdf0.92MB carzip.tistory.com remain)'.

Related