2017-06-22 40 views
2
// Example program 
#include <iostream> 
#include <string> 
#include <regex> 
int main() 
{ 
std::string strr("1.0.0.0029.443"); 

    std::regex rgx("([0-9])"); 
    std::smatch match; 

    if (std::regex_search(strr, match, rgx)) { 
     for(int i=0;i<match.size();i++) 
      std::cout << match[i] << std::endl; 
    } 
} 

这个程序应该写C++的正则表达式发现只有1分的比赛

1 
0 
0 
0 
0 
2 
9 
4 
4 
3 

但它写入

1 
1 

检查在这里http://cpp.sh/和视觉工作室,都同样的结果。

它为什么只找到2个匹配,为什么它们是相同的?


当我从这里了解答案,正则表达式搜索,在第一场比赛将停止,匹配变量保存必要的(子?)的字符串值,为其他的比赛继续(重复)。此外,由于它在第一场比赛中停止,所以只有在结果中使用子女比赛时,才会使用字母组合()

回答

4

被调用一次,regex_search只返回match变量中的第一个匹配项。 match中的集合包含匹配本身和捕获组(如果有的话)。

为了获得所有比赛在一个循环中调用regex_search

while(regex_search(strr, match, rgx)) 
{ 
    std::cout << match[0] << std::endl; 
    strr = match.suffix(); 
} 

注意,在你的情况下,第一个捕获组是一样的整场比赛所以该组中没有必要,你可以定义正则表达式仅仅作为[0-9](没有括号。)

演示:https://ideone.com/pQ6IsO

+0

它为什么只放1场搜索比赛拖入匹配变量?它在第一场比赛中停止搜索? –

+0

'\\ d'是'[0-9]' – AndyG

+0

稍微短一点的替代方案,非常感谢您提供这些重要信息。 –

1

问题:

  1. 使用if只能给你一个匹配。您需要使用while循环来查找所有匹配项。您需要在循环的下一次迭代中搜索前一场比赛。
  2. std::smatch::size()返回1+匹配数。见its documentationstd::smatch可以包含子匹配。要获取整个文本,请使用match[0]

这是你的程序的更新版本:

#include <iostream> 
#include <string> 
#include <regex> 

int main() 
{ 
    std::string strr("1.0.0.0029.443"); 

    std::regex rgx("([0-9])"); 
    std::smatch match; 

    while (std::regex_search(strr, match, rgx)) { 
     std::cout << match[0] << std::endl; 
     strr = match.suffix(); 
    } 
} 
+0

我想在C#中没有一行代码来获取所有与string.Split(stringArray,..) –

+0

@huseyintugrulbuyukisik,我没有编程在C#中的所有部分。我无法回应。 –