首先,在定義正則表達式時使用原始字符串文字以避免反斜線問題(\.
不是有效的轉義序列,您需要"\\."
或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個文字反斜槓,這些反斜槓將與輸入文本中的單個\
相匹配。
你應該避免反斜槓'\\\'。 –
雙轉義點並使用'regex_search'。 –
請發佈此例外的確切文本。還要注意你的字符串需要將反斜槓加倍。 –