2016-11-29 66 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

:)对不起,没注意。现在修复。 –