anuj
anuj

Reputation: 1060

using re.sub with groups

re.sub("([^\\[\s\\]]+)([\\]\s]*)( [>|=|<] )",replace(r'\1')+r'\2'+r'\3',s) 

This doesn't pass the first group to replace function and rather passes r'\1' as a string.

Please suggest what is going wrong.

Upvotes: 1

Views: 759

Answers (1)

user432
user432

Reputation: 3534

You are passing a string to the method replace.

The group will only be evaluated in the sub method. You could do a separate search to get your result, untested though since you have not posted the value from s nor the replace function:

pattern = "([^\\[\s\\]]+)([\\]\s]*)( [>|=|<] )"
re.sub(pattern, replace(re.search(pattern, s).group(1))+r'\2'+r'\3',s)

Here is another method possible better suited for you:

# this method is called for every match
def replace(match):
    group1 = match.group(1)
    group2 = match.group(2)
    group3 = match.group(3)
    # process groups
    return "<your replacement>"

s = "<your string>"
pattern = "([^\\[\s\\]]+)([\\]\s]*)( [>|=|<] )"
newtext= re.sub(pattern, replace, s)

print(newtext)

Upvotes: 5

Related Questions