我编写了以下程序来匹配C++中的正则表达式
#include <regex.h>
#include <iostream>
using namespace std;
/*
* Match string against the extended regular expression in
* pattern, treating errors as no match.
*
* return true for match, false for no match
*/
bool match(const char *string, char *pattern)
{
int status; regex_t re;
if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0)
return false;
/* report error */
status = regexec(&re, string, (size_t) 0, NULL, 0);
regfree(&re);
if (status != 0) {
return false; /* report error */
}
return true;
}
int main()
{
string str = "def fadi 100";
bool matchExp = match(str.c_str(), "^[Dd][Ee][Ff][' '\t]+[A-z]+([,])?[''\t]+[0-9]+$");
cout << (matchExp == true ? "Match": "No match") << endl;
}
Run Code Online (Sandbox Code Playgroud)
该程序正常工作正常,但当我使用带有-Wall -Werror参数的gcc编译代码(Linux环境)时,我收到一条非常恼人的警告消息,说明如下:
main.cpp: In function ‘int main()’:
main.cpp:33:90: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
Run Code Online (Sandbox Code Playgroud)
有没有办法强迫编译器相信它str.c_str()是一样的char * str?如果是这样,怎么样?
不,没有.该转换在C++ 03中已弃用,在C++ 11中是非法的; 不要这样做.
该转换的弃用来自字符串文字是只读的事实,因此const; 使用指向non的指针访问它们const char可能会导致修改const对象,从而调用未定义的行为.警告并不烦人 ; 它旨在帮助您避免可能导致应用程序崩溃 - 或者更糟.
另外,你在阅读警告信息时错了; 它不是关于c_str(),它是关于传递字符串文字char *.
要真正解决您的代码的唯一方法是改变的第二个参数你match是const char *不是char *和所传递的字符串到一个新的缓冲区,内部复制到该功能(为什么不main()呢?因为有内部缓冲区,你有较少的样板上来电者的一面).
我还想提出完全不同的解决方案,因为问题标记为"C++":Boost.Regex.