Extract specific string

早过忘川 提交于 2019-12-12 04:33:54

问题


I have the following QString that I want to extract only the access_token value which is "http%3a%2f%2fschemas.xmlsoap....." How to do that?

{"token_type":"http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0","access_token":"http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=asdasr21321214a%2f%2fschemas.microsoft.com%2faccwresscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&Audience=http%3a%2f%2fapi.microsofttranslator.com&ExpiresOn=1347332993&Issuer=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&HMACSHA256=sFqvp2a2xXc3VBdxYZ6xHQf%2fKkOydnuX6VK7A6Yf55k%3d","expires_in":"599","scope":"http://api.microsofttranslator.com"}


回答1:


Quick and dirty, only for demonstration of QString::section:

QString Data("{...you json data...}");
QString AccessToken = data.section("access_token\":\"",1).section("\"",0,0);

Consider: QString::section is slow and heavy, creating QStringList and converting tokens to RegExp in background. But I still do use it frequently in some cases.




回答2:


Check out QJson at http://qjson.sourceforge.net/.

You can easily parse a string into tokenized attributes. From the usage page:

QJson::Parser parser;
QString json = "{your json above}";
bool ok;
QVariant result = parser.parse (json, &ok);
qDebug() << result["access_token"].toString();

Have fun.




回答3:


Try this regex:

\"access_token\":\"([^\"]*)\"

explain:

( subexpression )
Captures the matched subexpression and assigns it a zero-based ordinal number.

[^ character_group ]
Negation: Matches any single character that is not in character_group. By default, characters in character_group are case-sensitive.



来源:https://stackoverflow.com/questions/12362151/extract-specific-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!