【问题标题】:Cannot find regex match C++找不到正则表达式匹配 C++
【发布时间】:2015-11-13 21:05:56
【问题描述】:

我是 C++ 的初学者并试图找到一个正则表达式匹配,但即使 xml 文件中有 94893274123 (没有空格)它也找不到匹配项。我不太确定它是否正确读取了 xml 文件...

 int main (){

 string line;
     ifstream infile("example.xml");
     if (infile.is_open()){
         ofstream outfile ("out.txt", ios_base::ate | ios_base::app); 
         if (outfile.is_open()){
             while (getline(infile, line)){
                 //ID
                 regex idnr (".*+<ID-Number>([0-9]+)<.*");
                 smatch id_match;
                 if (regex_match (line.cbegin(), line.cend(), id_match, idnr)){
                     cout << "Match found \n";
                 }
             }
         //closing all files
         outfile.close();
         infile.close();
         }
     else cout << "Unable to open output file\n";
     }
 else cout << "Unable to open input file\n";

 return 0;
}

程序运行返回 0 但仅此而已。我要做的是将xml文件分解为我需要的信息片段,稍后将其保存到变量或向量中,然后将它们重新组织到另一个文件中。

谢谢大家的回答...

【问题讨论】:

  • 请阅读how to ask 并描述什么不起作用。
  • 你说的不工作是什么意思?请发几个例子
  • 将“它不工作”替换为 1) 示例输入,2) 对您希望程序执行的操作的描述,以及 3) 对程序实际执行操作的描述。
  • 不好意思之前,发的比较着急……现在可以理解了吗?

标签: c++ regex xml string-matching


【解决方案1】:

以下代码在使用 Dev-C++ 5.11 编译时按预期工作(报告找到匹配项)(确保将代码生成设置为符合 GNU C++11。我所做的唯一更改是添加 #include 语句。

确保该文件位于执行代码可以找到它的目录中。您的 ifstream 构造函数是相对路径。 “example.xml”文件需要与程序运行所在的目录位于同一目录中。

#include <iostream>
#include <fstream>
#include <regex>
using namespace std;

 int main (){

     string line;
     ifstream infile("example.xml");
     if (infile.is_open()){
         ofstream outfile ("out.txt", ios_base::ate | ios_base::app); 
         if (outfile.is_open()){
             while (getline(infile, line)){
                 //ID
                 regex idnr (".*+<ID-Number>([0-9]+)<.*");
                 smatch id_match;
                 if (regex_match (line.cbegin(), line.cend(), id_match, idnr)){
                     cout << "Match found \n";
                 }
             }
         //closing all files
         outfile.close();
         infile.close();
         }
     else cout << "Unable to open output file\n";
     }
 else cout << "Unable to open input file\n";

 return 0;
}

使用 Visual Studio 2013 尝试相同的代码时出现一些错误。首先,转到 DEBUG->Project Properties->Configuration Properties->Debugging 并确保您的工作目录指向包含您正在解析的 example.xml 文件的目录。接下来看一下正则表达式的构造函数

regex idnr(".*+<ID-Number>([0-9]+)<.*");

句号-星号加序列会贪婪地消耗任何字符串并阻止序列其余部分的匹配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    相关资源
    最近更新 更多