php preg_match 在 Boost C++中等效?

php preg_match's equivalent in C++ with Boost?

本文关键字:C++ Boost preg match php      更新时间:2023-10-16

我有以下可用的php代码:

preg_match('/^(d+):/', $string, $matches)

然而,当我尝试在C++中使用Boost的regex库时,它不起作用。

regex expression1("^(\d+):"); 
std::string filename = "C:\Users\root\Desktop\something.bin";
std::ifstream ifs(filename.c_str(), std::ios::in | std::ios::binary);
std::string contents((std::istreambuf_iterator<char>(ifs)), 
std::istreambuf_iterator<char>());
cmatch what; 
if(regex_match(contents.c_str(), what, expression1))  
{ 
    cout<<"value is "<<what[1]<<endl;
} 

我不明白为什么。CCD_ 1与其他模式配合得很好,但与这一个CCD_ 2配合得不好。

字符在C字符串中开始转义。尝试"^(\d+):"

      | Single quotes |  Double quotes |
 -----+---------------+----------------+
  PHP |   string      |     string     |
      | (verbatim)    |                |
 -----+---------------+----------------+
  C++ |   char        |     string     |
 -----+---------------+----------------+

在PHP中使用单引号意味着d没有其特殊含义。

但是,您可以在C++中正确地使用双引号(您必须这样做,因为在C++中,单引号分隔字符,而不是字符串)。但现在您必须考虑令牌d的特殊含义。

转义反斜杠将解决您的问题:

regex expression("^(\d+):"); 

如果你使用双引号字符串,你也必须在PHP中这样做:

preg_match("/^(\d+):", $string, $matches);

你做错了。在字符串中使用反斜杠意味着需要对反斜杠进行转义。

尝试"^(\d+):"(两个反斜杠)

编辑:正如Berry所评论的,PHP单引号字符串中的d是完全合法的。我错误地认为这实际上是一个违规行为,但PHP会自动"帮助"您修复它。