2017-06-22 70 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#中的所有部分。我無法迴應。 –

相關問題