How to get substring from a string in qt?

老子叫甜甜 提交于 2019-12-05 22:15:10

问题


I have a text form:

Last Name:SomeName, Day:23 ...etc

From Last Name:SomeName, I would like to get Last Name, and separately SomeName.

I have tried to use QRegularExpression,

QRegularExpression re("(?<label>\\w+):(?<text>\\w+)");

But I am getting the result:

QString label = match.captured("label") //it gives me only Name

What I want is whatever text till ":" to be label, and after to be text.

Any ideas?


回答1:


You could use two different methods for this, based on your need:

  • split()
  • section()

main.cpp

#include <QString>
#include <QDebug>

int main()
{
    QString myString = "Last Name:SomeName, Day:23";
    QStringList myStringList = myString.split(',').first().split(':');
    qDebug() << myStringList.first() << myStringList.last();
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run

qmake && (n)make

Output

"Last Name" "SomeName"


来源:https://stackoverflow.com/questions/23033112/how-to-get-substring-from-a-string-in-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!