2015-01-13 3 views
1

저는 C에서 정규 표현식을 사용하여 분할 함수를 작성하려고합니다. 지금까지 나는 이것을 생각해 냈다.C + + 정규식을 사용하여 첫 번째 일치 색인을 찾으십시오

vector<string> split(string s, regex r) 
{ 
    vector<string> splits; 
    while (regex_search(s, r)) 
    { 
     int split_on = // index of regex match 
     splits.push_back(s.substr(0, split_on)); 
     s = s.substr(split_on + 1); 
    } 
    splits.push_back(s); 
    return splits; 
} 

내가 알고 싶은 것은 주석 처리 된 행을 입력하는 방법입니다.

답변

4

조금 더 필요 하겠지만 아래 코드의 주석을 참조하십시오. 당신이 일치하는 위치를 기억하기 위해, std::string에 일치하고 있기 때문에 남자 트릭, 여기 std::smatch을 일치하는 객체를 사용하는 것입니다 (다만 당신은 한하지가) : 이것은 너무처럼 사용할 수 있습니다

vector<string> split(string s, regex r) 
{ 
    vector<string> splits; 
    smatch m; // <-- need a match object 

    while (regex_search(s, m, r)) // <-- use it here to get the match 
    { 
    int split_on = m.position(); // <-- use the match position 
    splits.push_back(s.substr(0, split_on)); 
    s = s.substr(split_on + m.length()); // <-- also, skip the whole match 
    } 

    if(!s.empty()) { 
    splits.push_back(s); // and there may be one last token at the end 
    } 

    return splits; 
} 

:

auto v = split("foo1bar2baz345qux", std::regex("[0-9]+")); 

그리고 "foo", "bar", "baz", "qux"을 제공합니다.

std::smatchstd::match_results의 전문이며 참조 문서는 here입니다.

+0

감사합니다. 완벽하게 작동합니다. 나는 아직도 C++을 배우고 있는데 이것은 정말로 도움이된다. – Maurdekye

관련 문제