简体   繁体   English

re.sub不适用于特定的正则表达式模式

[英]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 : 在上面的代码中,我正在从csv读取outputpattern的值,其值为:

\\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)

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 您需要将CSV中的模式更改为\\ 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。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM