簡體   English   中英

使用regex_search從C ++中的XML文件中查找並輸出6個特定的時間戳

[英]Using regex_search to locate and output 6 specific time-stamps from an XML file in C++

在這個周末,我一直在嘗試使正則表達式熟悉,以便將其實施到C ++程序中,以提取6個特定的時間戳,不僅將它們輸出到控制台窗口,還將它們輸出到簡單輸出中文本文件。 到目前為止,我已經總結了以下內容。 但是,我在下面的內容僅將第一個時間戳打印到控制台窗口,並且也僅將第一個時間戳打印到輸出文件,而忽略其他5個。有人可以幫我找出我出了問題的地方嗎? http://regexr.com/上對其進行測試后,該正則表達式可以正常工作

XML檔案: http//pastebin.com/5hMy9RzK

當前狀態的控制台窗口的屏幕快照: http : //imgur.com/7YPJpoK

我嘗試提取的6個時間戳的屏幕快照: https : //i.imgur.com/G06NVlh.jpg

#include <fstream>
#include <string>
#include <iostream>
#include <regex>

using namespace std;

int main()

{
ifstream infile;
ofstream outFile;
string fileinput;
int i = 0;
outFile.open("Outputdata.txt");
infile.open("Groupproject.xml"); // Opens the XML file containing the information that is to be read

regex time_regex("\\d\\d\\d\\d-\\d\\d-\\d\\d\\w\\d\\d:\\d\\d:\\d\\d\\.716Z");

smatch time_matches;




if (infile.fail())
{
    cout << "The file is not able to be located" << endl;
    system("Pause");
    exit(1);
}


while (!infile.eof()) {  //Until the end of the file is reached, obtain each line
    getline(infile, fileinput);

    if (regex_search(fileinput, time_matches, time_regex)) { // if regex_search is able to locate a line which has elements matching the regex expression "time_regex" output the located element

    cout << "Timestamp: " << time_matches[i] << endl;
    outFile << time_matches[i];
    i++;
}

}
infile.close();
outFile.close();

system("pause");
return 0;
 }

我猜你的問題在這里: cout << "Timestamp: " << time_matches[i] << endl; outFile << time_matches[i]; i++; cout << "Timestamp: " << time_matches[i] << endl; outFile << time_matches[i]; i++;

請注意,您使用的是time_matches[i] ,其中i最初為0 (零)...,並且應始終為零...

但后來您增加它: i++;

time_matches[0]是與您的正則表達式匹配的所有內容的副本。

如果可以使用XML解析器,也請嘗試重新考慮使用正則表達式解析XML或HTML數據。

正則表達式是這項工作的錯誤工具,因為XML不是一種常規語言(從術語“計算機技術”的角度來說)。 使用XML解析器。 如果使用正則表達式,則程序將不正確。 它可能適用於10000個輸入文檔中的9999個,但遲早會失敗。 如果有人惡意發現您系統中的薄弱環節,那么它當然會很快失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM