找不到匹配的正则表达式

Cannot find regex match C++

本文关键字:正则表达式 找不到      更新时间:2023-10-16

我是c++的初学者,试图找到一个正则表达式匹配,但即使有<身份证号码> 94893274123 & lt;/ID-Number>(不带空格)在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 filen";
     }
 else cout << "Unable to open input filen";
 return 0;
}

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

使用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 filen";
     }
 else cout << "Unable to open input filen";
 return 0;
}

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

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

点号+星号序列将贪婪地消耗任何字符串,并阻止序列中其余部分的匹配。