[c++] C++에서의 정규 표현식과 콜백 함수
C++에서 정규 표현식을 사용하여 문자열을 처리하고, 콜백 함수를 통해 매칭된 결과를 처리하는 방법에 대해 알아보겠습니다.
정규 표현식과 std::regex
C++11부터 표준 라이브러리에 std::regex
클래스가 도입되었습니다. 이를 사용하여 문자열에서 패턴을 매칭하거나 검색할 수 있습니다.
#include <regex>
#include <iostream>
int main() {
std::string text = "The quick brown fox jumps over the lazy dog";
std::regex pattern("quick|brown|fox");
std::smatch matches;
if (std::regex_search(text, matches, pattern)) {
for (const auto& match : matches) {
std::cout << match << std::endl;
}
}
return 0;
}
위 코드는 주어진 텍스트에서 “quick”, “brown”, “fox” 중 하나의 단어가 존재하는지를 확인하고, 매칭된 결과를 출력합니다.
콜백 함수와 std::regex_iterator
std::regex_iterator
를 사용하면 정규 표현식에 매칭되는 모든 결과에 대해 반복적으로 콜백 함수를 호출할 수 있습니다.
#include <regex>
#include <iostream>
void callback(const std::smatch& match) {
std::cout << "Matched: " << match.str() << std::endl;
}
int main() {
std::string text = "The quick brown fox jumps over the lazy dog";
std::regex pattern("\\b\\w+\\b");
std::regex_iterator<std::string::iterator> it(text.begin(), text.end(), pattern);
std::regex_iterator<std::string::iterator> end;
while (it != end) {
callback(*it);
++it;
}
return 0;
}
위 코드는 주어진 텍스트에서 단어에 매칭되는 정규 표현식을 사용하여 모든 단어를 찾고, callback
함수를 통해 매칭된 결과를 출력합니다.
C++에서 정규 표현식과 콜백 함수를 사용하여 문자열 처리를 할 수 있습니다. 코드를 통해 각 단계를 자세히 살펴보았습니다.