开发者

Replace integer value via regular expression with python

开发者 https://www.devze.com 2023-02-11 13:41 出处:网络
Well, I am trying to apply some regular expression(search/replace) on xml. Yes I have to use some lib.\'s but in that case I cannot. My problem is ,as you may figure out, replacing value of node with

Well, I am trying to apply some regular expression(search/replace) on xml. Yes I have to use some lib.'s but in that case I cannot. My problem is ,as you may figure out, replacing value of node with an integer. When I try that, it gives me grouping error.Here are my patterns:

search pattern:

(<fieldset>)([^>].+)(<ipadd>)([^>].+)(<value>)([^>].+)(</value>)([^>].+)(</ipadd>)([^>].+)(</fieldset>)

replace pattern:

\1\2\3\4\5123.123.123.123\7\8\9\10\开发者_开发技巧11

As you see fifth group becomes "\5123" in replace pattern. And of course it doesn't work.

Well if I use something like this:

\1\2\3\4\5 123.123.123.123\7\8\9\10\11

It works. But I don't want a space or something else there.

And it also work with string:

\1\2\3\4\5foofoofoo\7\8\9\10\11

ah I am using re.sub() for replacing.

Is there a way that I can use it without spaces?

Thanks everyone


From Python Regular Expression operations - re.sub(pattern, repl, string[, count, flags])

In addition to character escapes and backreferences as described above, \g<name> will use the substring matched by the group named name, as defined by the (?P<name>...) syntax. \g<number> uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the RE.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号