I need to verify that a string line contains a specific word (M3), and this word contains a number in it. The problem is that the number is not always the same. Is there a way to verify a number in Qt C++?
I tried this, obviously not working:
if (line.contains("M"+"%i")) {
qDebug() << "contains the word";
}
You could use a regular expressions to search for certain patterns in a string. Since C++11 the C++ language contains a regular expression library that can be used to work with regular expressions.
Simple example:
#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;
}
Of course, if your numbers can be more than one digit, you will have to adjust the regular expression accordingly.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments