找不到正则表达式匹配C ++

时间:2015-08-20 09:31:02

标签: c++ regex xml string-matching

我在C ++中尝试并试图找到正则表达式匹配,但即使有< ID-号> 94893274123< / ID-号> (在xml文件中没有空格)它找不到匹配项。我不太确定它是否正确读取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文件粉碎成我需要的信息,稍后将其保存到变量或向量中,并将它们重新组织到另一个文件中。

感谢所有答案......

1 个答案:

答案 0 :(得分:0)

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

确保该文件位于执行代码可以找到它的目录中。你的ifstream构造函数是一个相对路径。 &#39; example.xml&#39;文件需要与运行程序的目录位于同一目录中。

#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-&gt;项目属性 - >配置属性 - &gt;调试并确保您的工作目录指向包含您正在解析的example.xml文件的目录。接下来,查看正则表达式构造函数

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

period-asterisk-plus序列将贪婪地使用任何字符串并阻止其余序列的匹配。