c++ - 正则表达式作为标记器 - 以分隔符开头的字符串

标签 c++ regex string c++11 tokenize

当子匹配的索引指定为 -1 时,sregex_token_iterator 几乎可以完美地用作分词器。但不幸的是,它不适用于以分隔符开头的字符串,例如:

#include <string>
#include <regex>
#include <iostream>
using namespace std;

int main()
{
    string s("--aa---b-c--d--");
    regex r("-+");

    for (sregex_token_iterator it = sregex_token_iterator(s.begin(), s.end(), r, -1); it != sregex_token_iterator(); ++it)
    {
        cout << (string) *it << endl;
    }

    return 0;
}

打印输出:

 
aa
b
c
d

(注意前导空行)。

因此请注意,它实际上可以很好地处理尾随分隔符(因为它不会打印额外的空行)。

阅读标准后,似乎有一个条款专门用于处理尾随定界符以使其正常工作,即:

[re.tokiter] 没有 4。

If the end of sequence is reached (position is equal to the end of sequence iterator), the iterator becomes equal to the end-of-sequence iterator value, unless the sub-expression being enumerated has index -1, in which case the iterator enumerates one last sub-expression that contains all the characters from the end of the last regular expression match to the end of the input sequence being enumerated, provided that this would not be an empty sub-expression.

有谁知道指定这种看似不对称行为的原因是什么?

最后,是否有一个优雅的解决方案来完成这项工作? (这样我们就没有空条目了)。

最佳答案

显然你的正则表达式匹配 - 分隔符之间的空字符串,一个简单的(不一定是优雅的解决方案)将丢弃所有长度为零的字符串:

...  
string aux = (string) *it;  
if(aux.size() > 0){  
    cout << aux << endl;  
}
...  

关于c++ - 正则表达式作为标记器 - 以分隔符开头的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9797294/

相关文章:

c++ - 稍后更新其中一个变量时,计算结果不会改变

java - Java中的正则表达式将特定的特殊字符与数字匹配

php - 在 PHP 中将数组的第一个元素转换为字符串

php - 使用 php 从数据库中的整数创建并回显一个字符串

c++ - 在 C++ 代码中使用嵌入式汇编语言进行错误分析

c++ - 转发引用的常量引用与转发引用的常量引用

c++ - sizeof 不会显示实际大小,尝试实现 ip

c# - 正则表达式匹配 C# 中的所有大写和下划线

python - 正则表达式中多个字符的重复累积和恒定(python)

string - 如何在String方法中打印原始go struct