How can I index group elements in re.sub?

时间:2015-10-06 08:19:08

标签: python regex

how can I index a character in a matched group from within the re.sub match.

So I am trying to do this:

import re
string_test = "this.day"
string_test = re.sub("^(.*?)\.(.*?)", "\g<1>[0].\g<2>", string_test)

My result should be: "t.day". Is it possible to somehow index the \g<1> group within the re.sub ? Obviously \g<1>[0] doesn't work.

2 个答案:

答案 0 :(得分:2)

You can't do indexing like above unless you use lambda function. Just change your regex like below.

string_test = re.sub("^(.)[^.]*\.(.*)", r"\g<1>.\g<2>", string_test)

or

>>> import re
>>> string_test = "this.day"
>>> re.sub(r"^(.)[^.]*\.(.*)", r"\1.\2", string_test)
't.day'

If you really want to do indexing,

>>> re.sub(r"^(.*?)\.(.*)", lambda m: m.group(1)[0] + '.' + m.group(2), string_test)
't.day'
>>> re.sub(r"^(.*?)(\..*)", lambda m: m.group(1)[0] + m.group(2), string_test)
't.day'

答案 1 :(得分:1)

No, you can't do that; but you can refactor the groups so they capture the parts that you do want.

string_test = re.sub("^(.).*?\.(.*?)", "\g<1>.\g<2>", string_test)

This is slightly more strict because it requires at least one character in the first group; but then so does your problem statement (so your original regex was erroneous in this regard, too).

相关问题