首先,在定义正则表达式时使用原始字符串文字以避免反斜线问题(\.
不是有效的转义序列,您需要"\\."
或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'。 –
请发布此例外的确切文本。还要注意你的字符串需要将反斜杠加倍。 –