1

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.

1
  • 4
    There's a saying going something like this: A programmer had a problem. He decided to solve it using regular expressions. Now the programmer have two problems. A regular expressions is a powerful tool in the right situation, but also very complex and prone to introducing bugs. In your case, you could simply find the position of the ':', then get the sub-string up to that position, and skip the first character (the '#'). It's simple and easy to write and debug. Commented Apr 3, 2019 at 8:52

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

why are you posting twice?... please, next time consider editing the answer instead of re posting the same answer....
2

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);
}

2 Comments

I tried it, a warning is unknown escape sequence '\#' appear
Sorry my bad, post has been edited by removing the extra slash (was copied wrongly from regex101.com)
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.