如何将c样式的正则表达式转换为c++样式
how do i convert a c# style regular expression to c++ style
我试图通过正则表达式解析一个长字符串,我尝试使用以下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。
:(
相关文章:
- 如何修复函数样式强制转换或类型构造的预期"("?
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- C 样式转换引用
- C++显式类型转换(C 样式强制转换)的强制表示法和static_cast的多种解释
- 枚举类的 C 样式强制转换到基础类型 char 的引用
- C++:禁用 CMake 中的旧样式转换警告
- 替换 c++ 中的 c 样式强制转换 (long&)
- Windows VC++编译器允许一种奇怪的c样式转换方式(或者它可能不是转换??)
- 重新解释强制转换和 C 样式转换之间的 C++ 区别
- 为什么使用运算符 class_name() 和 c 样式转换时 g++ 上出现错误
- 如何在 vim 中将 C 样式转换转换为C++样式转换
- C 样式转换是添加程序集(代码)还是仅供编译器了解情况
- 为什么C样式转换的行为与dynamic_cast不同
- 我可以使用C样式转换将派生类转换为私有基类吗
- 确定编译器为给定的C样式转换生成的内容
- 转换为枚举类型需要显式转换(static_cast、C样式转换或函数样式转换)
- 使用C++样式转换以所需的精度执行表达式的正确方法是什么
- 错误 C2274:使用 auto 进行 boost::p osix_time::time_duration 时出现"函数样式转换"的原因是什么?
- 函数调用参数中的构造函数样式转换
- 有没有办法在 c++ 中禁用旧的 c 样式转换