【发布时间】:2013-06-26 18:19:03
【问题描述】:
我编写了以下程序来匹配 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;
}
程序按预期工作正常,但是当我使用带有 -Wall -Werror 参数的 gcc 编译代码(Linux 环境)时,我收到一条非常烦人的警告消息,内容如下:
main.cpp: In function ‘int main()’:
main.cpp:33:90: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
有没有办法强制编译器相信str.c_str() 与char * str 相同?如果有,怎么做?
【问题讨论】:
-
不一样,你的代码是无效的C++11。
-
有多烦人?它告诉您您可能有未定义的行为。总比两年后随机停止工作而你不知道为什么要好。
-
为什么不做匹配函数 2 参数 const char * ?
-
编译器没有抱怨
str.c_str();警告是因为您试图将字符串文字"^[Dd]...[0-9]+$"分配给char *pattern参数。为什么模式需要是char *而不是char const*? -
@Praetorian 我是第一个
标签: c++