【问题标题】:Boost regex match with reading from file通过从文件中读取来提升正则表达式匹配
【发布时间】:2014-11-21 05:36:06
【问题描述】:

我在 C++ 中有以下代码,它应该逐行读取文件并匹配正则表达式以获取我正在寻找的信息。正如this link 所给出的,正则表达式是有效的,尽管程序没有找到它。这是程序:

#include <boost/regex.hpp> 
#include <iostream> 
#include <fstream>
int main() 
{ 
    boost::regex expr1("Property\(C\):\sIP\s\=(.*)\n");
    boost::smatch what1;
    std::string line;
    std::ifstream myfile("document.txt");
    if(myfile.is_open()){
        std::cout <<"FILE OPEN " <<std::endl;
        while(getline(myfile, line))
        {
            std::cout <<" LINE : " << line <<std::endl;
            if (boost::regex_search(line, what1, expr1)) 
            { 
                std::cout<<"MATCH FOUND " <<std::endl;
            for(int i(0); i<what1.size(); i++)
                std::cout << "WHAT " <<i<<" "<<what1[i] <<std::endl;
            }
        }
    }

}

该文件应该包含以下数据:

Property(C): IP = 127.0.0.1
Property(C): PORT = 9999
Property(C): CURRENTDIRECTORY = C:\Users\logpoint\Downloads\Compressed\command_lines_and_setups_source\Setup\Debug
Property(C): CLIENTUILEVEL = 0
Property(C): CLIENTPROCESSID = 28184
Property(C): VersionDatabase = 200

我的代码有什么问题吗?

【问题讨论】:

  • 不需要转义=,它不是特殊字符。您需要使用双反斜杠而不是简单的反斜杠。
  • 我是否也应该为空格字符添加双反斜杠
  • 是的,添加两个反斜杠有效,谢谢。
  • 是的,对于所有速记字符类:Property\\(C\\):\\sIP\\s=(.*)\\n

标签: c++ regex boost


【解决方案1】:

正如 Casimir et Hippolyte 所建议的,在我的正则表达式中添加两个反斜杠是可行的。即我的正则表达式是:

"Property\\(C\\):\\sIP\\s=(.*)"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-30
    • 2017-06-12
    • 2018-04-06
    • 2011-01-12
    • 1970-01-01
    • 2018-07-11
    相关资源
    最近更新 更多