【问题标题】:Regex C++: extract substring from a string then count each word正则表达式 C++:从字符串中提取子字符串,然后计算每个单词
【发布时间】:2015-02-17 17:39:00
【问题描述】:

我有以下格式的文本字符串。

*tag0 hi how are you tag1 where are you from tag3 i would like to eat some food*

文本位于向量中,我将其分配给变量字符串line2。我想从每个标签中提取单词并将其计为令牌。下面是我的代码。

smatch t_headermatch;
regex re("tag[0-9]+");

for (int i = 0; i < (int)boxraw.size(); ++i) {          
    line2 = boxraw.at(i); 

while (regex_search(line2, t_headermatch, re)){
        for (auto x : t_headermatch)cout << x << " ";

//If find tag header, print the words after the header and count it as token.

//repeat the process until found a new tag header.exit if no tag found


        cout <<endl;
        line2 = t_headermatch.suffix().str();
    }

我的预期输出如下所示:

Found 3 tag

tag0
hi token 1
how token 2
are token 3
you token 4
tag1
where 1 
are  2 
you 3
tag3 
i 1
would 2
like 3
to 4
eat 5
some 6
food 7

【问题讨论】:

    标签: c++ regex substring extract


    【解决方案1】:

    使用下面的正则表达式

    "tag\\d+((?:\\s+(?!tag)\\w+)+)"
    

    每个regex_search 都会返回match_result 对象

    t_headermatch[0] : the whole match, i.e. "tag0 hi how are you"
    t_headermatch[1] : the substring with tokens "hi how are you"
    

    你还需要拆分令牌等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 2010-10-14
      • 2020-09-15
      相关资源
      最近更新 更多