2015-10-17 106 views
2

我有一個字符串說:字符串比較使用正則表達式

std::string s1 = "@[email protected]";

我想與另一個字符串,但只有某些字符匹配它:

std::string s2 = "_Hello_World_";

的字符串必須具有相同的長度和完全匹配忽略可以是任何東西的_字符。換句話說,我想在相同的索引處匹配「Hello」和「World」的順序。

我可以在這裏使用循環忽略這些索引,但我想知道如果我可以用正則表達式來做到這一點?

+0

在正則表達式,點任何字符(除換行符)相匹配,所以你的正則表達式將不得不樣子'.Hello.World .'。 – Siguza

回答

1

是的,你可以只使用std::regex_match像這樣:

std::string string("@[email protected]"); 
std::regex regex("^.Hello.World.$"); 
std::cout << std::boolalpha << std::regex_match(string, regex); 

Live demo

.(點)在正則表達式的意思是 「任何字符」,^表示 「字符串的開始」,並$意味着字符串的結尾。

+0

也可以匹配任何小寫字符而不是任何字符嗎? – user963241

+1

@ user963241是的,[與類](http://coliru.stacked-crooked.com/a/551e20b1401797af)。如果您有任何其他問題,請打開一個新問題,而不是在這裏問問他們。原因是Stack Overflow針對單個直接問題+相關答案進行了優化;評論中的問題和答案可能甚至不會被搜索引擎索引。 – Shoe

+0

謝謝。我只想知道一件與答案有關的事情:如果確實需要在正則表達式中使用'^'和'$'。我認爲它沒有它們也行得通。 – user963241

0

'。' (點)運算符在正則表達式模式中將作爲任何字符的替代。下面你有3個字符串與由拍拍可變匹配不同的分隔符...

#include <iostream> 
#include <regex> 

using namespace std; 

int main() 
{ 
    regex pat(".Hello.World."); 
    // regex pat(.Hello.World., regex_constants::icase); // for case insensitivity 

    string str1 = "_Hello_World_"; 
    string str2 = "@[email protected]@"; 
    string str3 = "aHellobWorldc"; 

    bool match1 = regex_match(str1, pat); 
    bool match2 = regex_match(str2, pat); 
    bool match3 = regex_match(str3, pat); 

    cout << (match1 ? "Matched" : "Not matched") << endl; 
    cout << (match2 ? "Matched" : "Not matched") << endl; 
    cout << (match3 ? "Matched" : "Not matched") << endl; 


    //system("pause"); 
    return 0; 
}