1. 程式人生 > >[C/C++標準庫]_[初級]_[使用正則表示式過濾Windows檔名中的非法字元]

[C/C++標準庫]_[初級]_[使用正則表示式過濾Windows檔名中的非法字元]

場景

1.Windows和macOS的檔名有自己的命名規則, 特別是Windows的檔名限制了不允許使用的特殊字元. 在使用這些檔名新建檔案時會建立失敗.

說明

1.在前面的文章裡在Windows上我使用了比較笨的方法: 過濾Windows.MacOSX檔名中的非法字元. 最近發現其實使用正則效率更高.

例子


#include <regex>
#include <iostream>

// "[/|?%*\\\\\"<>\]"
template<typename T>
std::basic_string<T, std::char_traits<T>
, std::allocator<T> > ReplaceString(const T* text,const T* old,const T* _new){ std::basic_regex<T> pattern(old); std::basic_string<T, std::char_traits<T>, std::allocator<T> > rep(_new); std::basic_string<T, std::char_traits<T>, std::allocator<T>
> text1(text); std::basic_string<T, std::char_traits<T>, std::allocator<T> > tmp = std::regex_replace(text1,pattern,rep); return tmp; } int _tmain(int argc, _TCHAR* argv[]) { // 把 /T\\T\\T?T%T*T|T\"T<T> 裡的特殊字元替換為- std::string result = ReplaceString("/T\\T\\T?T
%T*T|T\"T<T>","[/|?%*\\\\\"<>\]","-"); std::cout << result << std::endl; system("pause"); return 0; }

輸出

-T-T-T-T-T-T-T-T-T-

參考