使用できることの 1 つは、「開始」と「終了」のインデックスを indexOf() で取得し、次のように使用することです。
QString x = "start some text here end";
QString s = "start";
QString e = "end"
int start = x.indexOf(s, 0, Qt::CaseInsensitive); // returns the first encounter of the string
int end = x.indexOf(e, Qt::CaseInsensitive); // returns 21
if(start != -1) // we found it
QString y = x.mid(start + s.length(), end);
または新しいリストを作成したくない場合は midRef 。「終了」も処理する必要がある場合があります。そうしないと、何も返さない 0 から -1 になる可能性があります。たぶん (終了 > 開始 ? 終了 : 開始)
編集:気にしないでください。end == -1 の場合は、最後まですべてを返すことを意味します (デフォルトでは、2 番目のパラメーターは -1 です)。これが望ましくない場合は、代わりに私の例を使用して、「終了」を選択するときに何らかの if ステートメントを使用できます。
編集:ドキュメントを読み間違えたことに気づきました。これはdefになります。仕事:
#include <QDebug>
int main(int argc, char *argv[]) {
QString x = "start some text here end";
QString s = "start";
QString e = "end";
int start = x.indexOf(s, 0, Qt::CaseInsensitive);
int end = x.indexOf(e, Qt::CaseInsensitive);
if(start != -1){ // we found it
QString y = x.mid(start + s.length(), ((end - (start + s.length())) > -1 ? (end - (start + s.length())) : -1)); // if you dont wanna pass in a number less than -1
or
QString y = x.mid(start + s.length(), (end - (start + s.length()))); // should not be any issues passing in a number less than -1, still works
qDebug() << y << (start + s.length()) << (end - (start + s.length()));
}
}
これにより、次の結果が生成されます。最後の 2 つの数字は、"start" が終わり、"end" が始まる場所です。
x = "ここからテキストを開始 end" => "ここからテキストを開始" 5 16
x = "一部のテキストはここで終わります" => アウトプリントなし
x = "testing start start some text here end" => "start some text here" 13 22
x = "テスト開始 ここからテキストを開始" => "ここからテキストを開始" 13 -14
または、正規表現を使用してそれを行うことができます。あなたのためにここに非常に簡単なスニペットを書きました:
#include <QDebug>
#include <QRegExp>
int main(int argc, char *argv[]) {
QRegExp rxlen("(start)(.*(?=$|end))");
rxlen.setMinimal(true); // it's lazy which means that if it finds "end" it stops and not trying to find "$" which is the end of the string
int pos = rxlen.indexIn("test start testing some text start here fdsfdsfdsend test ");
if (pos > -1) { // if the string matched, which means that "start" will be in it, followed by a string
qDebug() << rxlen.cap(2); // " testing some text start here fdsfdsfds"
}
}
これは、最後に「end」がある場合でも機能し、行末まで解析するだけです。楽しみ!