1

我正在尝试在代码中re从 C++中使用 python 的正则表达式包。boost.python这是我的 C++ 应用程序中的示例代码片段:

#include <boost/python.hpp>


Py_Initialize();
object main = import("__main__");
object main_namespace = main.attr("__dict__");

object ignored = exec(
        "import re\n"
        "def run():\n"
        "    rmatch = re.search(r'\d',r'hello3')\n"
        "    print rmatch\n"
        "\n"
        "print 'main module loaded'\n", main_namespace); 

object run_func = main.attr("run");
run_func(); 

Py_Finalize(); 

正则表达式应该简单地选取字符串中的数字hello3。这行代码在 Python 中有效,但在嵌入式 Python 中,rmatch始终是None.

谁能提供一些关于为什么的见解?谢谢!

4

2 回答 2

2

您需要替换\d\\d.

PS你为什么不直接使用boost.regex??

于 2012-11-16T15:49:31.227 回答
1

我认为您需要转义反斜杠:

"    rmatch = re.search(r'\\d',r'hello3')\n"

请记住,它首先由 C++ 编译器处理。当 Python 得到它时,它会看到\d一个换行符而不是\\dand \n。如果您不使用 Python 的原始字符串 ( r''),则必须将其编写为:

"    rmatch = re.search('\\\\d','hello3')\\n"
于 2012-11-16T15:58:40.230 回答