2013-08-21 29 views
0

我在VC++中使用正則表達式中的一個函數。這裏是我的代碼文件:regex_replace函數以不同的方式工作

#include "stdafx.h" 
#include<regex> 
#include<iostream> 
#include<string> 
using namespace std; 
void test_regex_search(const std::string& input) 
{ 
    std::cout << " Initial string = " << input <<endl; 
    std::regex rgx("(^|\\W)\\d+([a-zA-Z]*)?[\\\-\\\\]?(\\d*)([a-zA-Z]*)?"); 
     std::smatch match; 
    char start[200] = {0}; 
    std::string repalcewith(""); 
     if (std::regex_search(input.begin(), input.end(), match, rgx)) 
     { 
     std::cout << "match[0] = " << match[0]<< '\n'; 
     std::cout << "match[1] = " << match[1] << '\n';  
    } 
     else 
     std::cout << "No match\n"; 
    std::regex_replace(&start[0],input.begin(),input.end(),rgx,repalcewith); 
    std::cout << "final string = "<<start << endl; 
} 
int _tmain(int argc, _TCHAR* argv[]) 
{  
    test_regex_search("HIGH STREET 4323HTY KM3.5 WINES "); 
    return 0; 
} 

執行後,輸出出現這樣的: 最終的字符串= HIGH STREET KM3葡萄酒

在「KM3.5」字這種特殊情況下

爲什麼最終的字符串來了作爲「KM3」,而我的正則表達式不承認「。」?它是在處理「。」作爲空間或可能是這個原因的適當原因。 在此先感謝 Shashank

回答

0

.匹配\W在您的正則表達式開始。您可能需要使用\b代替(^|\W)

+0

感謝您的回覆。我的要求是刪除完整的單詞,如果它以數字開頭並且只需通過正則表達式完成。特別是當表達式遇到「KM3.5」時,它應該保存這個完整的單詞,因爲它是以一個字符開始的。而目前的行爲是將其轉換爲「KM3」,這與我的預期不同。我經歷了你的建議,但如果我用「\\ b」替換「^ | \\ W」,則「KM3.5」的結果爲「KM3」。這對我來說又是一個問題。 –

+0

定義「單詞」。 '\ W'類不認爲'.'是一個單詞字符。如果您的「單詞」的定義與'[A-Za-z0-9 _] +'不同,那麼您不能使用'\ W',但必須明確拼寫非單詞字符(根據您的定義)。 –

相關問題