gpt4 book ai didi

regex - Boost regex用于解析字符串中的键/值对

转载 作者:行者123 更新时间:2023-12-01 09:06:46 26 4
gpt4 key购买 nike

我尝试解析其键值对的以下字符串:

#include <iostream>
#include <string>
#include <map>

#include <boost/regex.hpp>

int main()
{
std::string deliveryReceipt = "id:pgl01130529155035239084 sub:001 dlvrd:001 submit date:1305291550 done date:1305291550 stat:DELIVRD err:0";

std::map<std::string, std::string> results;
boost::regex re("(?:([^:]+):([^,]+)(?:,|$))+"); // key - value pair

boost::sregex_iterator it(deliveryReceipt.begin(), deliveryReceipt.end(), re), end;
for ( ; it != end; ++it){
results[(*it)[1]] = (*it)[2];
}

std::map<std::string, std::string>::iterator resultsIter = results.begin();
while (resultsIter != results.end())
{
std::cout << "key:" << resultsIter->first << " value:" << resultsIter->second << std::endl;
resultsIter++;
}
}

我得到以下输出:

键:id值:pgl01130529155035239084子:001 dlvrd:001提交日期:1305291550完成日期:1305291550统计:DELIVRD错误:0

如何修复此正则表达式以正确解析键/值对?

最佳答案

我会选择这样的东西(更新了)
"\\s*(?<!\\S)([^:]+)\\s*:(\\S+)(?!\\S)"
https://regex101.com/r/Sufx5m/1

讲解

 \s*              # Optional whitespace trim
(?<! \S) # Whitespace boundary delimiter
# (also matches at beginning of string)
( [^:]+ ) # (1), Key - not any ':' colon chars
\s* # Optional whitespace trim
: # Colon
( \S+ ) # (2), Value - not whitespace chars
(?! \S ) # Whitespace boundary delimiter.
# (also matches at end of string)

关于regex - Boost regex用于解析字符串中的键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57931041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com