2016-11-29 30 views
1

獲取文件名我有這個簡單的程序未經檢查的異常,同時運行regex-不extention從文件路徑

string str = "D:\Praxisphase 1 project\test\Brainstorming.docx"; 
regex ex("[^\\]+(?=\.docx$)"); 
if (regex_match(str, ex)){ 
    cout << "match found"<< endl; 
} 

期待的結果是真實的,我的正則表達式工作,因爲我在網上試了一下,但是當試圖要在C++中運行,應用程序會拋出未經檢查的異常。

+0

你應該避免反斜槓'\\\'。 –

+0

雙轉義點並使用'regex_search'。 –

+0

請發佈此例外的確切文本。還要注意你的字符串需要將反斜槓加倍。 –

回答

1

首先,在定義正則表達式時使用原始字符串文字以避免反斜線問題(\.不是有效的轉義序列,您需要"\\."R"(\.)")。其次,regex_match需要全字符串匹配,因此使用regex_search

#include <iostream> 
#include <regex> 
#include <string> 
using namespace std; 

int main() { 
    string str = R"(D:\Praxisphase 1 project\test\Brainstorming.docx)"; 
    // OR 
    // string str = R"D:\\Praxisphase 1 project\\test\\Brainstorming.docx"; 
    regex ex(R"([^\\]+(?=\.docx$))"); 
    if (regex_search(str, ex)){ 
     cout << "match found"<< endl; 
    } 
    return 0; 
} 

C++ demo

注意R"([^\\]+(?=\.docx$))" = "[^\\\\]+(?=\\.docx$)",則\第一是文字反斜槓(你需要在正則表達式模式兩個反斜槓來匹配\符號),並在第二,需要4個反斜槓來聲明2個文字反斜槓,這些反斜槓將與輸入文本中的單個\相匹配。

+0

我猜他還想''D:\\ Praxisphase 1 project \\ test \\ Brainstorming.docx「' – Danh

+0

:)對不起,沒注意。現在修復。 –