Chinh Nguyen Huu
Chinh Nguyen Huu

Reputation: 133

Qt - How to get a string between 2 character?

I am working on Qt using string. How can I get a string between 2 characters are '#' and ':'

my strings below:

#id:131615165

#1:aaa,s1

#23:dd

#526:FE

the result that I want to get is: "id", "1", "23", "526".

Many thanks for any help.

Upvotes: 1

Views: 3575

Answers (4)

Amfasis
Amfasis

Reputation: 4208

I highly recommend an online regex-tester to start with the regex, for example: https://regex101.com

Using the following code you can capture the data from a QString:

QString input = "#id:131615165";
QRegExp test("#(.*):");
if(test.exactMatch(input))
{
    qDebug() << "result:" << test.cap(1);
}

Upvotes: 2

kefir500
kefir500

Reputation: 4404

Solution using QRegularExpression:

QRegularExpression regex("^#(.+?):");
qDebug() << regex.match("#id:131615165").captured(1);

Pattern explanation:

  • ^ matches the start of a line
  • # matches the # character
  • (.+?) is a capture group where:
    • . matches any character except line terminators
    • + matches one or more characters
    • ? is a "lazy" match to handle situations where multiple colons are present in the string.
  • : matches the : character

Upvotes: 3

Martin Hennings
Martin Hennings

Reputation: 16866

As @Someprogrammerdude wrote in the comments:

QString getTag(QString const &input)
{
    QString result;
    int idx = input.indexOf(':');
    if(input.startsWith('#') && idx > 1) {
        int len = idx - 1;
        result = input.mid(1, len); // [0]='#', [idx]=':'
    }
    return result;
}

Upvotes: 0

Dimitry Ernot
Dimitry Ernot

Reputation: 6594

QString based solution:

QString s("    #iddfg:131615165");
int startPos = s.indexOf('#') + 1;
int endPos = s.indexOf(':');
int length = endPos - startPos;
qDebug() << startPos << length << s.mid(startPos, length);

Upvotes: 3

Related Questions