Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Replace with regex

Tags:

python

regex

I need to replace part of a string. I was looking through the Python documentation and found re.sub.

import re s = '<textarea id="Foo"></textarea>' output = re.sub(r'<textarea.*>(.*)</textarea>', 'Bar', s) print output  >>>'Bar' 

I was expecting this to print '<textarea id="Foo">Bar</textarea>' and not 'bar'.

Could anybody tell me what I did wrong?

like image 249
Pickels Avatar asked Oct 22 '10 14:10

Pickels


People also ask

Can I use regex in replace Python?

Regex can be used to perform various tasks in Python. It is used to do a search and replace operations, replace patterns in text, check if a string contains the specific pattern.

Can you replace with regex?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.

How do you replace a pattern in Python?

Any string data can be replaced with another string in Python by using the replace() method. But if you want to replace any part of the string by matching a specific pattern then you have to use a regular expression.

What is regex in pandas replace?

replace() Pandas replace() is a very rich function that is used to replace a string, regex, dictionary, list, and series from the DataFrame. The values of the DataFrame can be replaced with other values dynamically. It is capable of working with the Python regex(regular expression). It differs from updating with .


1 Answers

Instead of capturing the part you want to replace you can capture the parts you want to keep and then refer to them using a reference \1 to include them in the substituted string.

Try this instead:

output = re.sub(r'(<textarea.*>).*(</textarea>)', r'\1Bar\2', s) 

Also, assuming this is HTML you should consider using an HTML parser for this task, for example Beautiful Soup.

like image 85
Mark Byers Avatar answered Sep 17 '22 00:09

Mark Byers