I'm dealing with a tough question. I need to delete some commas at the end of the line, which is previous some specific strings.
Such as:
define{
varA,
varB,
varC
}
The specific string is varC, and I want to delete varC and the comma(,) after varB at the same time.
The modified text is
define{
varA,
varB
}
I must deal with many code files so I need a script to do it, but that's tough for me.
You could use a regex that looks for the define
blocks, separating them in 3 groups:
define{...
and taking everything afterwards non-greedily, including newlines (so we'll need the re.DOTALL
flag to allow .
to match newlines)}
We just have to use re.sub
to replace the matches by the first and third groups only:
data = """
some code
some more code
define{
varA,
varB,
varC
}
some code
define{
varD,
varE
}
end of code
"""
import re
define_re = re.compile(r'(define{.*?)(,\s+\w+)(\s+})', re.DOTALL)
out = define_re.sub(r'\1\3', data)
print(out)
Output:
some code
some more code
define{
varA,
varB
}
some code
define{
varD
}
end of code
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.