정규식에서 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;
}
감사합니다. 이제 'str_to_modify'에 "123"이 있으면 잘 작동합니다. 그러나'str_to_modify'가 "ttt"을 가지고 있다면 나는 여전히 내가 기대했던 것을 얻지 못한다. 두 번째 예를 게시 할 것입니다. –