2016-11-08 117 views
-1

我需要驗證一個字符串行包含一個特定的單詞(M3),並且這個單詞包含一個數字。問題是這個數字並不總是相同的。有沒有辦法在Qt C++中驗證一個數字?如何在字符串中識別一個字母旁邊有一個數字?

我想這一點,顯然不是工作:

if (line.contains("M"+"%i")) { 
    qDebug() << "contains the word"; 
} 
+2

假設數字的值在i,''M「+ QString :: number(i)' – Thomas

+3

您的第一步是正式寫下您的要求。因爲它們太模糊,模糊不清,無法使用。例如,字符串「FOO BARM78 BAZ」是否包含您的魔語,或者不是?根據如何解釋這個問題,答案可以是肯定的,也可以不是。不知道需要做什麼,顯然不可能提供任何建議。 –

回答

0

你可以使用一個regular expressions搜索字符串中的某些模式。由於C++ 11 C++語言包含可用於使用正則表達式的regular expression library

簡單的例子:

#include <iostream> 
#include <regex> 
#include <string> 

int main() 
{ 
    std::string s; 
    //Fill s with the text you want to check for the pattern here! 
    // I'll use a fixed value here, but you'll need to change that. 
    s = "bla M5 bla"; 
    //regular expression for "letter M followed by one digit" 
    std::regex myRegex("M\\d"); 
    //std::regex_search checks whether there is a match between the 
    // given sequence s and the regular expression. Returns true, if 
    // there is a match. Returns false otherwise. 
    if (std::regex_search(s, myRegex)) 
    { 
    std::cout << "Text contains the search pattern.\n"; 
    } 
    else 
    { 
    std::cout << "Text does not contain the search pattern.\n"; 
    } 
    return 0; 
} 

當然,如果你的號碼可不止一個數字,你將不得不調整相應的正則表達式。

+0

感謝!這對我有很大的幫助,實際上我使用了另一個類,因爲我使用QT,其中一個名爲'QRegExp',就像'regex'一樣工作 – waroxx

相關問題