c++ - 将字符串中的数据提取到映射中的有效方法是什么?

标签 c++ regex string dictionary

这是用 C++ 编写的。假设我有一个看起来像这样的字符串 "[05]some words here [13]some more words here [17]and so on"

我想把这个字符串分割成Map<int, std::string>以数字作为键,将直到下一个代码的文本作为值。括号将被完全忽略。

到目前为止,我一直在使用标准库和 SDL(我正在制作一个小游戏),但我愿意安装 boost 或任何其他有帮助的库。

我的第一个想法是使用一些 Boosts Regex 函数来进行某种正则表达式查找和替换,或者简单地将其转换为字符数组,遍历每个字符查找括号并记录其中的数字,但这似乎好像它效率很低,特别是因为我确信在 C++ 中可能有一种流行的方法可以做到这一点。

最佳答案

您可以使用 regex_token_iterator为了这。基本思想如下:

#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <regex>

using namespace std;

map<int, string> extract( const std::string & s )
{
    map<int, string> m; 
    static const regex r( "\\s*\\[(\\d+)\\]" );
    sregex_token_iterator tok( s.begin(), s.end(), r, { -1, 1 } );
    tok++;  // Skip past the first end-of-sequence iterator.

    for( sregex_token_iterator end; tok != end; )
    {
        int num = stoi( *tok, nullptr, 10 );
        if( ++tok != end )
        {
            m.emplace( make_pair( num, *tok++ ) );
        }
    }
    return m;
}

int main()
{
    auto m = extract("[05]some words here [13]some more words here [17]and so on");
    for( auto & p : m ) cout << p.first << ": '" << p.second << "'" << endl;
    return 0;
}

这里,这是搜索并提取模式 \s*\[(\d+)\]\s*,这意味着它将删除方括号前后的所有空格,并且创建一个匹配组以匹配至少一位数字。

通过在迭代器上使用 {-1, 1},我们要求迭代序列提供匹配之前的所有文本,然后是匹配组 1。

输出:

5: 'some words here'
13: 'some more words here'
17: 'and so on'

工作示例是 here

关于c++ - 将字符串中的数据提取到映射中的有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43881407/

相关文章:

c++ - 在 Linux 中使用 Netbeans 调试具有 GUI 前端的 C++ 源代码

c++ - 一个类似 DSL 的小型 lisp,可以编译成 C/C++ 代码——Antlr 是一个不错的选择吗?

string - 字符串 slice 是否执行基础数据的复制?

javascript - 在 JS 中将字符串格式化为日期

python - 仅当列值是字符串时才将它们转换为小写

c++ - 外部库的 undefined reference (C++、QT、Ubuntu 14、CCV)

python - 用于识别 Reddit 用户名的正则表达式

javascript - 如何在JavaScript中匹配所有4字节UTF-8字符?

C 正则表达式如何匹配任何以“或任何空字符串结尾的字符串?

c++ - 在 OpenGL 中绘制单个像素