Python正则表达式字符串替换

时间:2018-01-09 22:58:59

标签: python regex

我有兴趣找到

的任何事件
#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>



int main()
{
    using namespace boost::lambda;
    typedef std::istream_iterator<int> in;

    std::for_each(
        in(std::cin), in(), std::cout << (_1 * 3) << " ");
}

并将其替换为

(somenumber)

我有一个Perl背景并试过这个,希望(\ d +)分组填充变量$ 1:

-somenumber

然而,这导致了文字的结果

myterm = re.sub(r"\((\d+)\)", "-\$1",myterm)

如何在Python中执行此操作?

1 个答案:

答案 0 :(得分:1)

我看到两个问题:

  1. 您正在使用Perl的语法(美元符号)取消引用位置匹配。 Python使用\,而非$

  2. Python编译器正在解释"-\$1中的反斜杠,并在re.sub看到它之前被有效删除。

  3. 使用原始字符串(如问题评论中所述)或转义反斜杠(通过双反斜杠),应该修复它:

    myterm = re.sub(r"\((\d+)\)", r"-\1", myterm)
    

    myterm = re.sub(r"\((\d+)\)", "-\\1", myterm)
    

    经过测试和确认:

    import re
    
    myterm = '(1234)'
    
    # OP's attempt:
    print re.sub(r"\((\d+)\)", "-\$1", myterm)
    
    # two ways to fix:
    print re.sub(r"\((\d+)\)", r"-\1", myterm)
    print re.sub(r"\((\d+)\)", "-\\1", myterm)
    

    打印:

    -\$1
    -1234
    -1234
    
相关问题