简体   繁体   中英

python re.sub not replacing string

I am trying to replace the string in a file like below, but somehow its not replacing

my_string = "TABLE "_$deleted$73$0"" --> inside can be any number, i wanted to change like below one

replace_string = "TABLE "I01""

o = "TABLE \"_$[a-z]+*$*\""
n = "TABLE \"I01\""

re.sub (o, n, file)

its not replacing that string, Pls help

Regards Kannan

Use raw strings to bypass Python's escape sequences (prefix the string literal with r ) This only bypasses Python's escape sequences, the Regex's special symbols still need to be escaped. Also, using a single quoted literal is cleaner as your pattern contains double quotation marks.

There were multiple issues with your pattern. Both the $ symbols must be prefixed with \ . Secondly, [az]+* has a + followed by a * which doesn't make sense, you don't need the * . The following is what seems to be the pattern as per the knowledge of one of its matches:

o =  r'TABLE "_\$[a-z]+\$\d+\$\d+"'

Let me know if something is not clear. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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