如何将c样式的正则表达式转换为c++样式

how do i convert a c# style regular expression to c++ style

本文关键字:样式 转换 c++ 正则表达式      更新时间:2023-10-16

我试图通过正则表达式解析一个长字符串,我尝试使用以下RE和链接中提到的文本http://regexr.com/3a7uf

但是,当我尝试使用相同的RE解析c++中的文本时,编译时警告和输出并不像预期的那样。

请建议如何将此RE排序为一种格式,以便在C++程序中解析文本。

代码如下:

std::string str = "root     21015  0.0  0.0      0     0 ?        S    "
    "16:07   0:00 [kworker/5:0]n            root     21095  0.0  0.0  "
    "    0     0 ?        S    16:08   0:00 [kworker/2:2]n            "
    "root     21097  0.0  0.0      0     0 ?        S    16:08   0:00 ["
    "kworker/u16:4]n            ashish   21103 17.1  1.2 591536 106056"
    " ?       Sl   16:12   0:01 /usr/lib/firefox/firefox";
std::regex firefox ("[0-9]...*.firefox");
std::smatch sm;
std::regex_match (str, sm, firefox);
std::cout << "number of matches: " << sm.size() << std::endl;
std::cout << "matches were: " << std::endl;
for (unsigned int i = 0; i < sm.size(); i++)
{
    std::cout << "[" << sm[i] << "]";
}

编译期间的警告如下:

warning: unknown escape sequence: '\.'
     regex firefox ("[0-9].\..*.firefox");

输出如下:

number of matches: 0
matches were:

此处需要使用双转义符。

[0-9].\..*.firefox

您必须转义反斜杠才能使其成为有效的C++字符串。例如,尝试:

std::regex firefox ("[0-9].\..*.firefox");

在我看来,这只是字符串处理方式的一个问题。你可以试试

std::regex firefox (@"[0-9]...*.firefox");

要指示它是字符串文字,或者如果不支持该语法,请尝试

std::regex firefox ("[0-9].\..*.firefox");

也就是说,你真的希望字符串中有一个字符,而不是转义符。

编辑

从下面的注释中,似乎C#语法不正确,或者句点是用来连接的(就像PHP?(,但它们在正则表达式中没有连接,而是占位符。

std::regex firefox ("[0-9]+[.][0-9]+[^.]*firefox");

你能在上面的示例中准确地(从开始到结束(突出显示你想要匹配的内容吗?我真的不知道你想从哪里开始匹配,但如果你试图找到数字和句点,上面的内容将从1.2开始。

感谢您的回复。这个表达本身没有错。

我只是使用了以下语法来创建正则表达式,它运行得很好。

std::regex otherProcessRegEx ("[0-9][0-9][:.:].*.[a-z].|[0-9][:.:].*.[a-z]",
               std::regex_constants::ECMAScript |     
               std::regex_constants::icase);

随着c++11的出现http://www.johndcook.com/blog/cpp_regex/需要指定的不同类型的RegEx。

:(