2016-08-13 56 views
1

我要承認使用正則表達式在文本文件中的一些行,但regex_match不匹配任何行,即使我用正則表達式靠山(「*」)Regex_match不匹配文件

string dirin = "/home/user/in.srt"; 
string dirout = "/home/user/out.srt"; 
ifstream in(dirin.c_str()); 
ofstream out(dirout.c_str()); 

string line; 
// regex patron("(\\d{2}):(\\d{2}):(\\d{2}),(\\d{3})\\s-->\\s(\\d{2}):(\\d{2}):(\\d{2}),(\\d{3})"); 
regex patron(".*"); 
smatch m; 
while (getline(in, line)) { 
    if (regex_match(line, m, patron)) { 
    out << "ok"; 
    }; 
    out << line; 
} 
in.close(); 
out.close(); 

代碼總是在out.srt文件中打印字符串行,但從不在if(regex_match(line,m,patron))中輸入字符串「ok」。 01: 我有以下行

00測試它00708 - > 00:01:01800

你看看那條河

00:01:02,977 - > 00:01:04,706

輕輕地流過。

00:01:06213 - > 00:01:08238

你注意到葉

+0

我們應該猜測你想要匹配什麼嗎? –

+0

我想匹配註釋行,但不匹配任何行 –

+0

@DiegoSilvera - 無法重現:使用您的代碼,所有行(空)也會生成一個「ok」 – max66

回答

1

注意getline()讀取與尾隨回車線CR符號,並注意ECMAScript .模式考慮到它是一個行結束符號,因此不符合CR符號。

regex_match要求整個字符串匹配模式。

因此,您需要在模式結尾考慮可選的回車。

regex patron("(\\d{2}):(\\d{2}):(\\d{2}),(\\d{3})\\s-->\\s(\\d{2}):(\\d{2}):(\\d{2}),(\\d{3})\\s*"); 

regex patron(".*\\s*"); 

另外,還要考慮使用原始字符串字面量,如果你的C++版本允許它:

regex patron(R"((\d{2}):(\d{2}):(\d{2}),(\d{3})\s-->\s(\d{2}):(\d{2}):(\d{2}),(\d{3})\s*)"); 
您可以通過在模式的結尾追加 \r?\s*
+1

這是問題所在,謝謝 –