首页 > 解决方案 > 用正则表达式在字符串中查找字符串,regex_search

问题描述

我有一个字符串:

string str = "C:/Riot Games/League of Legends/LeagueClientUx.exe" "--riotclient-auth-token=yvjM3_sRqdaFoETdKSt1bQ" "--riotclient-app-port=53201" "--no-rads" "--disable-self-update" "--region=EUW" "--locale=en_GB" "--remoting-auth-token=13bHJUl7M_u_CtoR7v8XeA" "--respawn-command=LeagueClient.exe" "--respawn-display-name=League of Legends" "--app-port=53230" "--install-directory=C:\Riot Games\League of Legends" "--app-name=LeagueClient" "--ux-name=LeagueClientUx" "--ux-helper-name=LeagueClientUxHelper" "--log-dir=LeagueClient Logs" "--crash-reporting=crashpad" "--crash-environment=EUW1" "--crash-pipe=\\.\pipe\crashpad_12076_CFZRMYHTBJGPBIUH" "--app-log-file-path=C:/Riot Games/League of Legends/Logs/LeagueClient Logs/2020-07-13T13-33-41_12076_LeagueClient.log" "--app-pid=12076" "--output-base-dir=C:\Riot Games\League of Legends" "--no-proxy-server";

我想获取端口号和远程身份验证令牌,我使用以下代码执行此操作:

#include <regex>
#include <iostream>
#include <string>
#include <Windows.h>

using namespace std;

string PrintMatch(std::string str, std::regex reg) {
    smatch matches;
    while (regex_search(str,matches,reg))
    {
        cout << matches.str(1) << endl;
        break;
    }

    return matches.str(1);

}


int main() {
    
    string str = "C:/Riot Games/League of Legends/LeagueClientUx.exe" "--riotclient-auth-token=yvjM3_sRqdaFoETdKSt1bQ" "--riotclient-app-port=53201" "--no-rads" "--disable-self-update" "--region=EUW" "--locale=en_GB" "--remoting-auth-token=13bHJUl7M_u_CtoR7v8XeA" "--respawn-command=LeagueClient.exe" "--respawn-display-name=League of Legends" "--app-port=53230" "--install-directory=C:\Riot Games\League of Legends" "--app-name=LeagueClient" "--ux-name=LeagueClientUx" "--ux-helper-name=LeagueClientUxHelper" "--log-dir=LeagueClient Logs" "--crash-reporting=crashpad" "--crash-environment=EUW1" "--crash-pipe=\\.\pipe\crashpad_12076_CFZRMYHTBJGPBIUH" "--app-log-file-path=C:/Riot Games/League of Legends/Logs/LeagueClient Logs/2020-07-13T13-33-41_12076_LeagueClient.log" "--app-pid=12076" "--output-base-dir=C:\Riot Games\League of Legends" "--no-proxy-server";
    
regex reg("([0-9][0-9][0-9][0-9][0-9])");
    

        string port = PrintMatch(str, reg);

    
regex reg1("(remoting-auth-token=[^\d]*)");

    string output = PrintMatch(str, reg1);
        








}

'

给我以下输出:

    53201
remoting-auth-token=13bHJUl7M_u_CtoR7v8XeA--respawn-comman

端口号(53201)中的字符数量没有改变,所以我成功地得到了。但是,remoting-auth-token 发生了变化,因此我不知道如何在更改长度时也成功获得它。

我想从远程身份验证令牌中获取这部分:“13bHJUl7M_u_CtoR7v8XeA”,所以我可以将它存储在一个变量中以便在我的应用程序中使用,就像我对端口号所做的那样。

期待您的回音!:)

标签: c++regex

解决方案


您应该研究预期匹配的语法以正确提取它们。

要获取端口号值,我会使用

regex reg("--riotclient-app-port=(\\d+)");

这样,您甚至不需要关心匹配的位数,因为它会在已知字符串之后捕获一个数字。

如果身份验证令牌只能包含字母、数字,_或者-您可以使用

regex reg1("remoting-auth-token=([\\w-]+)")

where\w匹配字母/数字/_-匹配连字符,+将匹配一个或多个匹配项。

请参阅C++ 演示


推荐阅读