我有一个字符串,格式如下
qString路径= https://user:pass@someurl.com
我想使用QRegExp从上面的路径输入用户名和密码。也曾处理过以下案件
1. qString path = http://user:pass@someurl.
在以下情况下,如果不包含任何用户名或passwod,则返回字符串。
2. qString path = https://someurl.com我的代码是与http和https一起工作的,是否有任何最好的方法可以做到这一点既简短又简单。请建议
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);
}发布于 2018-03-22 12:15:34
它可以用QUrl来实现。
下面的函数操作URL 权威格式
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;
}那就叫吧
QUrl oUrl("https://user:pass@someurl.com");
std::cout<< GetFixedUrl(oUrl).toString().toStdString()<< std::endl;产出将是:
https://someurl.com发布于 2018-03-22 12:58:02
我建议两种方法。你可以选择一个更方便,更适合你:
使用正则表达式的
QString removeAuthority1(const QString &path)
{
QRegExp rx("((http|https|ftp):\\/\\/)(.*@)?(.*)");
if (rx.indexIn(path) != -1) {
return rx.cap(1) + rx.cap(4);
}
return QString();
}使用 QUrl
QString removeAuthority2(const QString &path)
{
QUrl url = QUrl::fromUserInput(path);
return url.scheme() + "://" + url.host();
}使用
QString path("http://user:pass@someurl.com");
QString s1 = removeAuthority1(path); // http://someurl.com
QString s2 = removeAuthority2(path); // http://someurl.comhttps://stackoverflow.com/questions/49427952
复制相似问题