regex 라이브러리
c++ 11 부터 정규 표현식(regex)을 처리하기 위한 표준 라이브러리가 제공되었는데, <regex> 헤더 파일에 정의되어 있으며, 다음과 같은 기능을 제공한다.
•
문자열 내에서 패턴 매칭
•
매칭된 부분 문자열의 위치 및 길이 검색
•
매칭된 부분 문자열 추출
•
정규 표현식을 이용한 검색과 치환
예제) “Hello, World!” 문자열에서 “Hello”를 찾는 예제
#include <iostream>
#include <regex>
using namespace std;
int main() {
string str = "Hello, World!";
regex re("Hello");
if (regex_search(str, re) {
cout << "Found match!\n";
else {
cout << "No match found.\n";
}
return 0;
}
C++
복사
regex_search 함수
•
문자열에서 패턴을 검색
•
패턴이 문자열에 있을 경우 true 를 반환, 없으면 false
예제)
#include <iostream>
#include <regex>
using namespace std;
int main() {
string str = "The quick brown fox jumps over the lazy dog";
regex re("\\b([a-z]+)\\b"); // 소문자 단어 패턴 정의
smatch matches;
while (regex_search(str, matches, re)) {
string match = matches[1].str();
// 대문자로 변환
transform(match.begin(), match.end(), match.begin(), ::toupper);
replace(matches.position(1), match.length(), match);
}
cout << str << '\n';
return 0;
}
C++
복사
smatch 클래스
•
매칭된 부분 문자열을 저장하는 컨테이너
regex_search()
•
함수를 호출할때 ‘matches’ 인자를 전달하면, 매칭된 부분 문자열이 ‘matches’에 저장된다.
regex_transform()
•
이후 이 함수를 사용하여 매칭된 문자열을 대문자로 변환하고
string::replace()
•
이 함수를 사용하여 원본 문자열에서 해당 부분 문자열을 대문자로 바꾼다.