c++qthttphttpsqregexp

Ingore string using QRegExp


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

Solution

  • 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