2016-02-09 91 views
-1

我有一個未格式化的推文列表(僅從網站複製粘貼),我試圖將每條推文分隔到自己的個人行中,除去文本文件中的所有其他無關細節。在C++中使用正則表達式搜索.txt文件

我目前有一個正則表達式字符串,當我通過記事本++進行搜索時,但由於某種原因,我無法通過C++獲得它。

我通過搜索文本的例子如下:

Autotestdrivers.com ‏@testdrivernews Nov 6 

Tesla Model S third row of seats confuses,… http://dlvr.it/CgTbsL #children #models #police #tesla #teslamotors #Autos #Car #Trucks 

1 retweet 3 likes 

Gina Stark ✈ ‏@SuuperG Nov 6 

Ha! Kinda. @PowayAutoRepair I have a thing for "long-nose" cars; #Porsche #Jaguar #Ferrari , and I love the lines of a #Tesla! 

View conversation 

0 retweets 2 likes 

Tony Morice ‏@WestLoopAuto Nov 6 

\#WeirdCarNews via @Therealautoblog Tesla Model S third row of seats confuses, delights police http://www.autoblog.com/2015/11/06/tesla-model-s-third-row-seats-police/ … 

View summary 

0 retweets 0 likes 

我用正則表達式採取鳴叫被張貼的日期和鳴叫本身,看起來像這樣:

[A-Z][a-z][a-z] \d+\r\n\r\n *.+\r\n 

...但由於某種原因,我不能讓它在我的代碼中工作。

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

std::regex rgx("[A-Z][a-z][a-z]\\d+\\r\\n\\r\\n *.+\\r\\n"); 

    std::string Location_Of_Tweet = "put location here"; 
    std::smatch match; 
    std::cout << twitterFile; 

    std::ifstream twitterFiler; 

    twitterFiler.open(Location_Of_Tweet,std::ifstream::in); 

    const std::string tweetFile((std::istreambuf_iterator<char>(twitterFiler)), std::istreambuf_iterator<char>()); 
    if (std::regex_search(tweetFile.begin(), tweetFile.end(), match, rgx)) 
    { 
     std::cout << "Match\n"; 

     for (auto m : match) 
     std::cout << " submatch " << m << '\n'; 
    } 
    else 
     std::cout << "No match\n"; 
+0

你能否解釋有關_「我不能讓它在我的代碼工作」 _好嗎?具體問題是什麼?編譯器錯誤?運行時錯誤?意外的結果?請發佈[MCVE],其中包括所有錯誤消息verbaitm。 –

+0

抱歉不清楚。該代碼確實編譯和運行,唯一的問題是,正則表達式沒有找到任何匹配(我知道這是在.txt文件中)。我編輯完整的代碼。 – jimo337

+0

你使用哪個編譯器和版本?例如。 GCC 4.8仍然存在'std :: regex'實現的問題。另外,如果其他人想要測試它,示例代碼甚至不會編譯。 –

回答

1

這個正則表達式假定C++ 11正則表達式理解水平空白符\h
如果不是,請將所有\h替換爲[^\S\r\n]

這被鬆散地解釋爲什麼可能工作。
但是,您需要更實質性的分隔符來分隔推文。

"(?m)([A-Z][a-z][a-z]\\h+\\d+)\\h*\\r?\\n\\s*^\\h*(?=\\S)(.+)"

解釋使用您的樣品

(?m)        # Multi-line mode 
([A-Z] [a-z] [a-z] \h+ \d+)  # (1), Date 
\h* \r? \n \s*      # Line break, any number of whitespace 
^ \h*        # Beginning of line 
(?= \S)       # Next, first non-whitespace 
(.+)        # (2), Tweet 

測試用例。
輸出

** Grp 1 - (pos 37 , len 5) 
Nov 6 
** Grp 2 - (pos 46 , len 132) 
Tesla Model S third row of seats confuses,… http://dlvr.it/CgTbsL #children #models #police #tesla #teslamotors #Autos #Car #Trucks 

----------------- 

** Grp 1 - (pos 226 , len 5) 
Nov 6 
** Grp 2 - (pos 235 , len 126) 
Ha! Kinda. @PowayAutoRepair I have a thing for "long-nose" cars; #Porsche #Jaguar #Ferrari , and I love the lines of a #Tesla! 

----------------- 

** Grp 1 - (pos 435 , len 5) 
Nov 6 
** Grp 2 - (pos 444 , len 170) 
\#WeirdCarNews via @Therealautoblog Tesla Model S third row of seats confuses, delights police http://www.autoblog.com/2015/11/06/tesla-model-s-third-row-seats-police/ …