2013-06-10 3 views
1

내가 가지고 올 수있는 최선 : 출력C에서 정규 표현식 검색 및 바꾸기 + +?

#include <boost/algorithm/string/replace.hpp> 
#include <boost/regex.hpp> 
#include <iostream> 

using namespace std; 

int main() { 
    string dog = "scooby-doo"; 
    boost::regex pattern("(\\w+)-doo"); 
    boost::smatch groups; 
    if (boost::regex_match(dog, groups, pattern)) 
     boost::replace_all(dog, string(groups[1]), "scrappy"); 

    cout << dog << endl; 
} 

:

scrappy-doo 

.. 두 가지 검색을 수행 포함하지 않는이 일을 간단한 방법이 있나요? 어쩌면 새로운 C++ 11 자료 (gcc atm과 호환되는지 확실하지 않지만)

답변

2

std::regex_replace 트릭을해야합니다. 제공되는 예제는 여러분의 문제에 매우 가깝습니다. 원한다면 대답을 정확히 cout으로 밀어 넣는 방법을 보여줄 수도 있습니다. 후손을 위해 여기에 붙여 넣습니다.

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

int main() 
{ 
    std::string text = "Quick brown fox"; 
    std::regex vowel_re("a|e|i|o|u"); 

    // write the results to an output iterator 
    std::regex_replace(std::ostreambuf_iterator<char>(std::cout), 
         text.begin(), text.end(), vowel_re, "*"); 

    // construct a string holding the results 
    std::cout << '\n' << std::regex_replace(text, vowel_re, "[$&]") << '\n'; 
} 
+1

있습니다. 이전 인터페이스에서 정규식 그룹을 나타 내기 위해 $ x 구문을 사용하여 새로운 문자열을 효과적으로 다시 작성해야하기 때문에이 인터페이스는 반 직관적입니다. 그 말은, 나는 더 나은 것을 생각할 수 없다. – mavix