In re. Sub, you need to specify a substitution for the whole matching string. That means that you need to repeat the parts that you don't want to replace.
This works: myRe = re. Compile(r"(myFunc\(.+? \,.
+? \,)(.+? )(\,.
+? \,. +?
\,. +? \,.
+? \))") print myRe. Sub(r'\1"noversion"\3', val).
If you want to do this without using regex: >>> s = "myFunc('element','node','elementVersion','ext',12,0,0)" >>> l = s. Split(",") >>> l2="'noVersion'" >>> s = ",". Join(l) >>> s "myFunc('element','node','noVersion','ext',12,0,0).
– Paulo Scardine Dec 20 '10 at 11:26 3 Then, all the answers, including the regular expression ones, fail. :) – dheerosaur Dec 20 '10 at 11:28 you are right! That is why I think a parser is best suited to this task than a regular expression.
– Paulo Scardine Dec 20 '10 at 11:41 @Paulo, Yes, parsers, if available for the work at hand, should be preferred over regex. – dheerosaur Dec 20 '10 at 12:03.
Read the documentation: re. Sub returns a copy of the string where every occurrence of the entire pattern is replaced with the replacement. It cannot in any case modify the original string, because Python strings are immutable.
Try using look-ahead and look-behind assertions to construct a regex that only matches the element itself: myRe = re. Compile(r"(?+? \,)(.+?
)(?=\,. +? \,.
+? \,. +?
\,. +? \))").
If there is some chance of an argument containing a comma, the regex approach gets harder and harder. – Paulo Scardine Dec 20 '10 at 11:45.
If your only tool is a hammer, all problems look like nails. A regular expression is a powerfull hammer but is not the best tool for every task. Some tasks are better handled by a parser.In this case the argument list in the string is just like a Python tuple, sou you can cheat: use the Python builtin parser: >>> strdata = "myFunc('element','node','elementVersion','ext',12,0,0)" >>> args = re.
Search(r'\((^\)+)\)', strdata). Group(1) >>> eval(args) ('element', 'node', 'elementVersion', 'ext', 12, 0, 0) If you can't trust the input ast. Literal_eval is safer than eval for this.
Once you have the argument list in the string decontructed I think you can figure out how to manipulate and reassemble it again, if needed.
docs.python.org/howto/regex.html#search-... Hopefully that will let you just target the 3rd match.
A regular expression is a powerfull hammer but is not the best tool for every task. Some tasks are better handled by a parser. If you can't trust the input ast.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.