我在C++ Windows項目(Visual Studio 2010)中使用std::regex_replace
。代碼如下所示:std :: regex_replace給了我意想不到的結果
std::string str("http://www.wikipedia.org/");
std::regex fromRegex("http://([^@:/]+\\.)?wik(ipedia|imedia)\\.org/", std::regex_constants::icase);
std::string fmt("https://$1wik$2.org/");
std::string result = std::regex_replace(str, fromRegex, fmt);
我希望result
是"https://www.wikipedia.org/"
,但我得到"https://www.wikipedia.wikipedia.org/"
。
快速檢查與sed
給了我預期的結果
$ cat > test.txt
http://www.wikipedia.org/
$ sed 's/http:\/\/([^@:\/]+\.)?wik(ipedia|imedia)\.org\//https:\/\/$1wik$2.org\//' test.txt
http://www.wikipedia.org/
我不明白其中的差異從何而來。我檢查了可以與std::regex_replace
一起使用的標誌,在這種情況下我沒有看到任何幫助。
更新
這些變體做工精細:
std::regex fromRegex("http://([^@:/]+\\.)wik(ipedia|imedia)\\.org/", std::regex_constants::icase);
std::regex fromRegex("http://((?:[^@:/]+\\.)?)wik(ipedia|imedia)\\.org/", std::regex_constants::icase);
std::regex fromRegex("http://([a-z]+\\.)?wik(ipedia|imedia)\\.org/", std::regex_constants::icase);
std::regex fromRegex("http://([^a]+\\.)?wik(ipedia|imedia)\\.org/", std::regex_constants::icase);
BU不是這些:
std::regex fromRegex("http://([^1-9]+\\.)?wik(ipedia|imedia)\\.org/", std::regex_constants::icase);
std::regex fromRegex("http://([^@]+\\.)?wik(ipedia|imedia)\\.org/", std::regex_constants::icase);
std::regex fromRegex("http://([^:]+\\.)?wik(ipedia|imedia)\\.org/", std::regex_constants::icase);
這是沒有意義的,我......
您使用的是哪種編譯器?如果是GCC放棄:''*未實施*。改用boost。 –
我不知道任何編譯器都支持正則表達式。這是對編譯器的最新更新嗎? –
@sftrabbit MSVC的STL自2008版以來已經實現了一個功能正則表達式實現,並且LLVM/Clang的libC++也具有完整的正則表達式實現。 – rubenvb