Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python re.sub question

Tags:

python

regex

Greetings all,

I'm not sure if this is possible but I'd like to use matched groups in a regex substitution to call variables.

a = 'foo'
b = 'bar'

text = 'find a replacement for me [[:a:]] and [[:b:]]'

desired_output = 'find a replacement for me foo and bar'

re.sub('\[\[:(.+):\]\]',group(1),text) #is not valid
re.sub('\[\[:(.+):\]\]','\1',text) #replaces the value with 'a' or 'b', not var value

thoughts?

like image 649
netricate Avatar asked Jan 19 '10 16:01

netricate


People also ask

How do you're sub in Python?

To replace a string in Python, the regex sub() method is used. It is a built-in Python method in re module that returns replaced string. Don't forget to import the re module. This method searches the pattern in the string and then replace it with a new given expression.

What does re sub () do?

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.

Does re sub replace all occurrences?

sub() Replace matching substrings with a new string for all occurrences, or a specified number.

What does \b mean in Python re?

Inside a character range, \b represents the backspace character, for compatibility with Python's string literals. \B. Matches the empty string, but only when it is not at the beginning or end of a word.


1 Answers

You can specify a callback when using re.sub, which has access to the groups: http://docs.python.org/library/re.html#text-munging

a = 'foo'
b = 'bar'

text = 'find a replacement for me [[:a:]] and [[:b:]]'

desired_output = 'find a replacement for me foo and bar'

def repl(m):
    contents = m.group(1)
    if contents == 'a':
        return a
    if contents == 'b':
        return b

print re.sub('\[\[:(.+?):\]\]', repl, text)

Also notice the extra ? in the regular expression. You want non-greedy matching here.

I understand this is just sample code to illustrate a concept, but for the example you gave, simple string formatting is better.

like image 156
Christian Oudard Avatar answered Oct 06 '22 00:10

Christian Oudard