如何指定qstring :: indexof方法不对两个单词之间的空格数敏感?
题
我已经写了一个源代码,如:
int main(int argc, char *argv[]) {
QFile File (directory + "/File");
if(File.open(QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream Stream (&File);
QString FileText;
do
{
FileText = Stream.readLine();
QString s = "start";
QString e = "end here";
int start = FileText.indexOf(s, 0, Qt::CaseInsensitive);
int end = FileText.indexOf(e, Qt::CaseInsensitive);
if(start != -1){ // we found it
QString y = FileText.mid(start + s.length(), (end - (start + s.length())));
qDebug() << y << (start + s.length()) << (end - (start + s.length()));
}
.
}
我的问题在这里,int end= filetext.indexof(e,qt :: catepsensisive);
刚刚找到了QString e = "end here";
,当“结束”单词与“此处”之间有完全三个空格时,请找到。这是问题的,因为在文本中,我读取这两个词之间的空格肯定会不时不同。此外,我需要写两个单词“结束”和“在这里”。我试图减少问题的基础,希望有人有一个想法/解决方案。
解决方案
将空间间隔数缩短为1使用 QString::simplified()
方法。
其他提示
你也可以尝试 qregexp :
#include <QDebug>
#include <QString>
#include <QRegExp>
int main()
{
QString text("start ABCDE1234?!-: end here foo bar");
// create regular expression
QRegExp rx("start\\s+(.+)\\s+end\\s+here", Qt::CaseInsensitive);
int pos=0;
// look for possible matches
while ((pos=rx.indexIn(text, pos)) != -1) {
qDebug() << rx.cap(1); // get first match in (.+)
pos+=rx.matchedLength();
}
return 0;
}
. 不隶属于 StackOverflow