1

I have a string in following format

qString path = https://user:pass@someurl.com

I want to ingore username and password from the the above path using QRegExp. An worked with following case also

1. qString path = http://user:pass@someurl.

In the below case if it is does not contain any user name or passwod then return the string

2. qString path = https://someurl.com

My code is worked with http and https, Is there any best approach to do that is short and simple manner. please suggest

f(Path.startsWith("https://") == true)
{
    QRegExp UserPwd("(.*)(https://)(.*)(.*)", Qt::CaseInsensitive, QRegExp::RegExp);
    QRegExp UserPwd1("(.*)(https://)(.*)@(.*)", Qt::CaseInsensitive, QRegExp::RegExp);

    if(UserPwd1.indexIn(ErrorString) != -1)
    {
        (void) UserPwd1.indexIn(Path);
        return UserPwd1.cap(1) + UserPwd1.cap(2) + UserPwd1.cap(4);
    }
    else
    {
        (void) UserPwd.indexIn(Path);
        return UserPwd.cap(1) + UserPwd.cap(2) + UserPwd.cap(3);
    }
}
else
{
    QRegExp UserPwd("(.*)(http://)(.*)@(.*)", Qt::CaseInsensitive, QRegExp::RegExp);
    (void) UserPwd.indexIn(Path);
    return UserPwd.cap(1) + UserPwd.cap(2) + UserPwd.cap(4);
}

2 Answers2

2

It can be achieved using QUrl

The following function manipulate the URL authority format

QUrl GetFixedUrl(const QUrl & oUrl )
{
    QUrl oNewUrl = oUrl;

    // Reset the user name and password
    oNewUrl.setUserName(QString());
    oNewUrl.setPassword(QString());

    // Save the host name
    QString oHostName = oNewUrl.host();

    // Clear authority
    oNewUrl.setAuthority(QString());

    // Set host name
    oNewUrl.setHost(oHostName);

    return oNewUrl;

}

Then call it

QUrl oUrl("https://user:pass@someurl.com");

std::cout<< GetFixedUrl(oUrl).toString().toStdString()<< std::endl;

Output will be:

https://someurl.com
Simon
  • 1,522
  • 2
  • 12
  • 24
1

I would suggest two approaches. You can choose one, which is more convenient and suitable to you:

Using regular expression

QString removeAuthority1(const QString &path)
{
  QRegExp rx("((http|https|ftp):\\/\\/)(.*@)?(.*)");
  if (rx.indexIn(path) != -1) {
    return rx.cap(1) + rx.cap(4);
  }
  return QString();
}

Using QUrl

QString removeAuthority2(const QString &path)
{
  QUrl url = QUrl::fromUserInput(path);
  return url.scheme() + "://" + url.host();
}

Usage

QString path("http://user:pass@someurl.com");
QString s1 = removeAuthority1(path); // http://someurl.com
QString s2 = removeAuthority2(path); // http://someurl.com
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • what happens if my path contains some text example "How I can extract username and password from the path http://username:pass@someurl.com". I want to remove username and password rest thing same. In that case the above approach is not work. – Prabhat Chauhan Apr 11 '18 at 07:06
  • It should work with regular expression approach. However your path should still start with `http://` – vahancho Apr 11 '18 at 07:10