Qt是否提供了确定两个字符串匹配的方法? 例如:
bool res = isMatched( "Hello World", "World", Qt::MatchContains );
答案 0 :(得分:2)
要确定一个字符串是否包含另一个字符串,您可以使用QString::contains
:
QString str = "Hello World";
bool res = str.contains("World", Qt:::CaseSensitive); // returns true
您还可以使用QString::compare
来比较字符串。如果第一个字符串小于,等于或大于第二个字符串,则返回小于,等于或大于零的整数:
int x = QString::compare(str1, str2, Qt::CaseInsensitive);
答案 1 :(得分:0)
没有方法可以使用Qt::MatchFlags
来比较字符串,因为Qt::MatchFlags
仅用于特殊目的:在表格中查找项目。
这些标记包含仅对表有意义的Qt::MatchWrap
和Qt::MatchRecursive
,而不仅仅是2个字符串。
答案 2 :(得分:0)
我在最近的一个项目中需要这个,并编写了一个可以轻松添加到任何程序的函数。以下是代码的链接:http://sirspot.com/?p=324 并假设未来没有任何变化......这是代码本身:
/** determine if the pattern matches the string using Qt::MatchFlags
\param str the string
\param pattern the pattern to find
\param flags any combination of the follow Qt flags
- Qt::MatchFixedString
- Qt::MatchContains
- Qt::MatchStartsWith
- Qt::MatchEndsWith
- Qt::MatchRegExp (overrides all flags above)
- Qt::MatchCaseSensitive
\returns true if the pattern is found in the string
requires:
#include <QString>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
Thank you for visiting sirspot.com
This code is not guaranteed to work.
Use at your own risk.
*/
static bool QString_Matches(
const QString& str,
const QString& pattern,
const Qt::MatchFlags& flags = (Qt::MatchCaseSensitive | Qt::MatchFixedString))
{
if(flags.testFlag(Qt::MatchRegExp) == true)
{
QRegularExpression::PatternOptions options = QRegularExpression::NoPatternOption;
if(flags.testFlag(Qt::MatchCaseSensitive) == false)
{
options = QRegularExpression::CaseInsensitiveOption;
}
QRegularExpression regex(pattern, options);
return regex.match(str).hasMatch();
}
else
{
Qt::CaseSensitivity cs = Qt::CaseSensitive;
if(flags.testFlag(Qt::MatchCaseSensitive) == false)
{
cs = Qt::CaseInsensitive;
}
if(flags.testFlag(Qt::MatchContains) == true)
{
return str.contains(pattern, cs);
}
else
{
if(flags.testFlag(Qt::MatchStartsWith) == true)
{
if(str.startsWith(pattern, cs) == true)
{
return true;
}
}
if(flags.testFlag(Qt::MatchEndsWith) == true)
{
if(str.endsWith(pattern, cs) == true)
{
return true;
}
}
if(flags.testFlag(Qt::MatchFixedString) == true)
{
return (str.compare(pattern, cs) == 0);
}
}
}
return false;
};
快乐的字符串匹配!