2010-01-13 6 views
1

정규식에서 if-then-else 조건문을 이해하는 데 어려움이 있습니다.If-Then-Else 조건부 정규식 및 캡처 그룹 사용

If-Then-Else Conditionals in Regular Expressions을 읽은 후 간단한 테스트를 작성하기로 결정했습니다. 나는 C++, Boost 1.38 Regex 및 MS VC 8.0을 사용한다.

이 나는이 프로그램을 작성했습니다 :

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

int main() 
{ 
    std::string str_to_modify = "123"; 
    //std::string str_to_modify = "ttt"; 
    boost::regex regex_to_search ("(\\d\\d\\d)"); 
    std::string regex_format ("(?($1)$1|000)"); 

    std::string modified_str = 
     boost::regex_replace(
      str_to_modify, 
      regex_to_search, 
      regex_format, 
      boost::match_default | boost::format_all | format_no_copy); 

    std::cout << modified_str << std::endl; 

    return 0; 

} 

내가 str_to_modify가 "123"을 가지고 있는데 str_to_modify은 "TTT를"경우 "000"을 얻기 위해 "123"경우에 얻을 것으로 예상. 그러나 나는 첫 번째 경우에는 123123 000을, 두 번째 경우에는 아무 것도 얻지 못한다.

당신이 나에게 말해줘, 제발, 내 시험에 뭐가 잘못 됐니?

여전히 작동하지 않는 두 번째 예 :

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

int main() 
{ 
    //std::string str_to_modify = "123"; 
    std::string str_to_modify = "ttt"; 
    boost::regex regex_to_search ("(\\d\\d\\d)"); 
    std::string regex_format ("(?1foo:bar"); 

    std::string modified_str = 
     boost::regex_replace(str_to_modify, regex_to_search, regex_format, 
      boost::match_default | boost::format_all | boost::format_no_copy); 

    std::cout << modified_str << std::endl; 

    return 0; 

} 

답변

4

은 내가 Boost.Regex docs에 설명 된대로 형식 문자열이 (?1$1:000)을해야한다고 생각합니다.

편집 : 나는 regex_replace이 원하는 것을 할 수 없다고 생각합니다. 대신에 다음을 시도해보십시오. regex_match은 일치 여부를 알려주거나 match[i].matched을 사용하여 i 번째 태그 된 하위 표현식이 일치하는지 여부를 확인할 수 있습니다. match.format 멤버 함수를 사용하여 일치 항목의 서식을 지정할 수 있습니다.

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

int main() 
{ 
    boost::regex regex_to_search ("(\\d\\d\\d)"); 

    std::string str_to_modify; 
    while (std::getline(std::cin, str_to_modify)) 
    { 
     boost::smatch match; 
     if (boost::regex_match(str_to_modify, match, regex_to_search)) 
      std::cout << match.format("foo:$1") << std::endl; 
     else 
      std::cout << "error" << std::endl; 
    } 
} 
+0

감사합니다. 이제 'str_to_modify'에 "123"이 있으면 잘 작동합니다. 그러나'str_to_modify'가 "ttt"을 가지고 있다면 나는 여전히 내가 기대했던 것을 얻지 못한다. 두 번째 예를 게시 할 것입니다. –