我需要验证字符串行是否包含特定单词(M3),并且该单词中包含一个数字。问题是这个数字并不总是一样的。有没有办法在Qt C ++中验证一个数字?
我试过这个,显然不起作用:
if (line.contains("M"+"%i")) {
qDebug() << "contains the word";
}
答案 0 :(得分: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;
}
当然,如果您的数字可以超过一位数,则必须相应地调整正则表达式。