-1
我需要验证一个字符串行包含一个特定的单词(M3),并且这个单词包含一个数字。问题是这个数字并不总是相同的。有没有办法在Qt C++中验证一个数字?如何在字符串中识别一个字母旁边有一个数字?
我想这一点,显然不是工作:
if (line.contains("M"+"%i")) {
qDebug() << "contains the word";
}
我需要验证一个字符串行包含一个特定的单词(M3),并且这个单词包含一个数字。问题是这个数字并不总是相同的。有没有办法在Qt C++中验证一个数字?如何在字符串中识别一个字母旁边有一个数字?
我想这一点,显然不是工作:
if (line.contains("M"+"%i")) {
qDebug() << "contains the word";
}
你可以使用一个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;
}
当然,如果你的号码可不止一个数字,你将不得不调整相应的正则表达式。
感谢!这对我有很大的帮助,实际上我使用了另一个类,因为我使用QT,其中一个名为'QRegExp',就像'regex'一样工作 – waroxx
假设数字的值在i,''M“+ QString :: number(i)' – Thomas
您的第一步是正式写下您的要求。因为它们太模糊,模糊不清,无法使用。例如,字符串“FOO BARM78 BAZ”是否包含您的魔语,或者不是?根据如何解释这个问题,答案可以是肯定的,也可以不是。不知道需要做什么,显然不可能提供任何建议。 –