简体   繁体   中英

Python: String replacement with REGEX

I am new to python & I want to perform following actions.

I have bunch of text files with statements like

insert dynamic-variable; //Note that dynamic-variable is dynamic word i want to use as it is in my replacement statement.

I want to replace above statement with

Util.insert(dynamic-variable) ;

What is best possible way to get this done in python ? I am going through REGEX & Backreferance documentation but some specific direction will be helpful.

So, I am trying something of this sort

import re
input = "insert account;"
result = re.sub(r'((?:insert))(\w+);', r'Util.insert(\2);', )

result string should be Util.insert( account );

input = "insert contact;"
result = re.sub(r'((?:insert))(\w+);', r'Util.insert(\2);', )

result string should be Util.insert( contact );

(question edited, so first explanation is moot..., but now it's not working because of missing space characters in regex... plus non-capturing group isn't what you need, you need to consume insert to replace by Util.insert )

Okay, just create one capture group: the variable name

Working regex & example:

import re

s = "insert variable;"
print(re.sub("^insert\s+(\w+)",r"Util.insert(\1)",s))

prints:

Util.insert(variable);

(\\w+) matches any letter, digit and underscore, which probably covers the variables you can define.

try the following:-

import re

doc='''insert dynamic-variable;
insert dynamic-variable;
insert dynamic;
insert variable;
some more line
insert dynamic-variable;'''

print re.sub(r'insert\s([\w-]*)', r'Util.insert(\1);', doc)

Output:-

Util.insert(dynamic-variable);
Util.insert(dynamic-variable);
Util.insert(dynamic);
Util.insert(variable);
some more line
Util.insert(dynamic-variable);

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