当子匹配的索引指定为 -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/