Ishu Gupta
Ishu Gupta

Reputation: 1091

re.sub not working for a particular regex pattern

I am using following code :

re.sub(inputpattern,outputpattern, currentline)

in the above code , i am reading the value of outputpattern from csv , whose value is :

\\1-\\2-\\3-\\4

I am reading it like below :

outputpattern = row['PREFIX_1_WRT_FMT']

I have also tried :

outputpattern = "'"+ row['PREFIX_1_WRT_FMT'] +"'"

The problem is that it is not treating it as proper format , but if I hard code it like below it works fine :

re.sub(inputpattern,'\\1-\\2-\\3-\\4', currentline)

Upvotes: 0

Views: 130

Answers (1)

Meitham
Meitham

Reputation: 9670

You only need to escape the backslashes if you have it as a literal string.

"\\1-\\2-\\3-\\4"

If you read it from an input you don't have to do that. You need to change the pattern inside the CSV to be like \1-\2-\3-\4

You could also use the raw string if you dislike escaping every char when using literal string, by prefixing you string with the letter r.

r"\1-\2-\3-\4"

Upvotes: 1

Related Questions