2012-12-20 27 views
2

我在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); 

這是沒有意義的,我......

+2

您使用的是哪種編譯器?如果是GCC放棄:''*未實施*。改用boost。 –

+0

我不知道任何編譯器都支持正則表達式。這是對編譯器的最新更新嗎? –

+1

@sftrabbit MSVC的STL自2008版以來已經實現了一個功能正則表達式實現,並且LLVM/Clang的libC++也具有完整的正則表達式實現。 – rubenvb

回答

3

有一個微妙正則表達式中的錯誤。不要忘記編譯器擴展字符串文字中的轉義序列。所以改變

"http://([^@:/]+\.)?wik(ipedia|imedia)\.org/" 

"http://([^@:/]+\\.)?wik(ipedia|imedia)\\.org/" 

也就是說,有一對反斜線的替換每個兩個單反斜槓。

編輯:這似乎並沒有影響到這個問題,但。在我嘗試的兩個實現(Microsoft和clang)中,原始問題不會發生,而我們沒有加上反斜槓。 (如果沒有,會得到有關無效轉義序列的編譯器警告,但生成的.通配符與目標序列中的.字符匹配,就像\.一樣)

+1

或者改變它來使用原始文字 - 它幫助傾斜的牙籤問題:R的 「http://([^ @:/] + \。)WIK(ipedia | IMEDIA)\。組織/?」。注意前面的R. – emsr

+0

@emsr - 當然,如果你有一個支持原始文字的C++ 11編譯器。 –

+0

我的評論實際上是錯誤的,我刪除了它 – Julien

相關問題