python re.sub缺少组名错误

时间:2013-08-24 02:42:45

标签: python regex

我疯了我不知道为什么我会收到这个错误:

Traceback (most recent call last):
  File "File.py", line 154, in <module>
    main()
  File "File.py", line 143, in main
    dld = work()
  File "File.py", line 100, in work
    string1= re.sub(find_dev_line, dev_line_to_replace, string1)
  File "C:\Program Files (x86)\python27\lib\re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "C:\Program Files (x86)\python27\lib\re.py", line 270, in _subx
    template = _compile_repl(template, pattern)
  File "C:\Program Files (x86)\python27\lib\re.py", line 257, in _compile_repl
    raise error, v # invalid expression
sre_constants.error: missing group name

使用以下代码行:

dev_line_searchterm = "^.+"+devname+".+$"
dev_line_to_replace = str(os.path.join(start_dir, "Downloads", devname, filename))
find_dev_line = re.compile(dev_line_searchterm, re.MULTILINE)
string1= re.sub(find_dev_line, dev_line_to_replace, string1)

我在这些行中没有任何组,为什么我会收到错误?

1 个答案:

答案 0 :(得分:2)

dev_line_to_replace可能包含一些对正则表达式引擎有意义的特殊字符。您应该使用devname转义dev_line_to_replacere.escape,以避免在搜索或替换模式中出现特殊字符。