13. 정규표현식
1. 문자열 일치 확인
2. 문자열 숫자 검색
3. 문자열 일부 변경
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
regex re1(R"(l|i|k|e)");
regex re2(R"(\D)");
regex re3(R"(\s)");
string str = "i like coding";
string result1 = regex_replace(str, re1, "[$&]");
string result2 = regex_replace(str, re1, "*");
string result3 = regex_replace(str, re2, "_$&_");
string result4 = regex_replace(str, re3, "(space)");
cout << "result1: " << result1 << endl;
cout << "result2: " << result2 << endl;
cout << "result3: " << result3 << endl;
cout << "result4: " << result4 << endl;
return 0;
}
4. 첫 번째 결과 변경
5. 모든 숫자 검색
#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace std;
int main() {
regex re(R"(\d+)");
const string str = "12 34ab 56 cd78__ !9 10 ==11";
vector<string> result;
smatch match_info;
auto start = str.begin();
auto end = str.end();
while (regex_search(start, end, match_info, re)) {
result.push_back(match_info.str());
start = match_info[0].second;
}
for (auto i : result)
cout << i << ' ';
cout << endl;
return 0;
}
6. 특정 글자 검색 1
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
string str =
"Wang Geon, a descendant of Go-gu-ryeo nobility, deemed the nation as the successor of Go-guryeo ";
smatch match_info;
regex re(" Go-([^ ]*)");
while (regex_search(str, match_info, re)) {
cout << match_info.str() << ' ' << endl;
str = match_info.suffix().str();
}
return 0;
}
7. 특정 글자 검색 2
#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> Korea = {
"Republic of Korea",
"republic of Korea",
"Republic of korea",
"republic of korea",
"South Korea",
"south Korea",
"South korea",
"south korea",
};
regex re("([Rr]epublic)\\s.*");
smatch match_info;
for (auto i : Korea) {
if (regex_match(i, match_info, re))
cout << match_info[0] << endl;
}
return 0;
}
8. 특정 글자 검색 3
#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> Korea = {
"Republic of Korea",
"republic of Korea, since 1945",
"Republic of korea, since 1945",
"republic of korea",
"South Korea, since 1945",
"south Korea",
"SOUTH KOREA, since 1945",
"south korea",
};
regex re("(SOUTH|south).*(1945)");
smatch match_info;
for (auto i : Korea) {
if (regex_match(i, match_info, re))
cout << match_info[0] << endl;
}
return 0;
}
9. 모든 단어 검색
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
string str =
"Jolbon Buyeo was the predecessor to Goguryeo, and in 538, Baekje renamed itself Nambuyeo (South Buyeo)";
regex re("([A-Za-z]+)");
auto start = sregex_iterator(str.begin(), str.end(), re);
auto end = sregex_iterator();
cout << "== 단어 개수: " << distance(start, end) << " ==" << endl;
for (sregex_iterator i = start; i != end; ++i)
cout << i->position() << ", " << i->str() << endl;
return 0;
}