Home > Mobile >  Using regex to replace strings that include curly brackets
Using regex to replace strings that include curly brackets

Time:02-17

I'm absolutely new with regex, so you can imagine my confusion. I'm trying to use it to replace a substring in a string with another substring. This is the string:

string = "good books including ${good_book} should be read."

I would like to replace ${good_book} with "crime and punishment". How can I do that?

CodePudding user response:

I use this page to help me build regular expression: https://rubular.com/ They are super powerful but still complex.

Hopefully we can do it using simple code. This is an example:

import re

replaces = {
 "${good_book}" : "crime and punishment"
}
string = "good books including ${good_book} should be read."
regExpValue = "(\${[A-Za-z_] })"

def replace_choice(m):
    if (m.group() in replaces):
        return replaces[m.group()]
    else:
        print("Value not found in replace object! {}".format(m.group()))
        return None

print(re.sub(regExpValue, replace_choice, string))

the value for regular expression allows any tag enclosed in ${ ... } and supports replacements in replaces object. I state in the regex code that tag name can use A-Z (uppercase A-Z letters) a-z (lowercase A-Z letters) and "_" underscore. Any other character will not match here, but you can include them. Enclosed in brackets makes it an entity for character value and the " " sign in the end means that there should appear at least one of this chatacters for tag name. For instance, the tag ${any_VALUE} will be found, but the tag ${} has no match and the tag ${this-is-a-tag} has no match as well unless you include "-" to the tag characters.

CodePudding user response:

You have a lot of solutions simplier than regex. Like :

phrase = "good books including ${good_book} should be read."
phrase.replace('${good_book}','crime and punishment')

Or even better :

book_title = 'crime and punishment'
phrase = f'good books including {book_title} should be read.'

And with regex :

book_title = 'crime and punishment'  
phrase = "good books including {book_title} should be read." 
regex = '\{.*?\}' 
new_phrase = re.sub(regex,book_title,phrase)
  • Related