找到你要的答案

Q:re.sub() error related to MatchObject.group()

Q:再次,sub()误差相关group() MatchObject。

I have a very simple job for re.sub(), but am not able to get it to work correctly.

import re
print re.sub(r"\d+", lambda x:x, "1 2 3 4 5")

The matched strings should be printed as-is, so the expected output is:

1 2 3 4 5

The error I am getting is :

Traceback (most recent call last):
  File "_.py", line 2, in <module>
    print re.sub(r"\d+", lambda x:x, "1 2 3 4 5")
  File "/home/radar/anaconda/lib/python2.7/re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: sequence item 0: expected string, _sre.SRE_Match found

我是一个非常简单的工作。sub(),但我不能让它正常工作。

import re
print re.sub(r"\d+", lambda x:x, "1 2 3 4 5")

匹配的字符串应打印为,所以预期的输出是:

1 2 3 4 5

我得到的错误是:

Traceback (most recent call last):
  File "_.py", line 2, in <module>
    print re.sub(r"\d+", lambda x:x, "1 2 3 4 5")
  File "/home/radar/anaconda/lib/python2.7/re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: sequence item 0: expected string, _sre.SRE_Match found
answer1: 回答1:

The replacement function is passed a match object by re.sub(). You return that match object directly, while you must return a string instead; after all that is what is going to be used to replace (substitute) the original match.

You could return the matched text, via the MatchObject.group() method:

print re.sub(r"\d+", lambda x: x.group(), "1 2 3 4 5")

You have not clearly stated you expected to happen, however; the above will return the original string, as it replaces each digit with itself:

>>> re.sub(r"\d+", lambda x: x.group(), "1 2 3 4 5")
'1 2 3 4 5'

or you could increment the number by one (which requires conversion to an integer, then after manipulation, conversion back to a string):

>>> re.sub(r"\d+", lambda x: str(int(x.group()) + 1), "1 2 3 4 5")
'2 3 4 5 6'

替代功能是通过重新通过匹配对象。sub()。你直接返回匹配对象,而你必须返回一个字符串,毕竟这是用来替换(替代)原来的匹配。

你可以返回匹配的文本,通过MatchObject group()方法:

print re.sub(r"\d+", lambda x: x.group(), "1 2 3 4 5")

你还没有明确说明你预期会发生,但是,上述将返回原来的字符串,因为它取代了每个数字本身:

>>> re.sub(r"\d+", lambda x: x.group(), "1 2 3 4 5")
'1 2 3 4 5'

或者你可以增加一个数(需要转换为整数,然后经过处理,转换回字符串):

>>> re.sub(r"\d+", lambda x: str(int(x.group()) + 1), "1 2 3 4 5")
'2 3 4 5 6'
answer2: 回答2:
re.sub(r"\d+", lambda x: x.group(), "1 2 3 4 5")
re.sub(r"\d+", lambda x: x.group(), "1 2 3 4 5")
python  regex