정규 표현식
필요이유
어떤 문자열이 우리가 원하는 형식인지 아는 것은 입출력데이터를 처리할때 중요한 문제이다.
ex) 주어진 문자열이 이메일 주소인가?, 전화번호 형식인가?
전 시간에 했던 입력 유효성 검사 방법으로도 처리 할 수도 있겠지만, 번거롭기도 하고 쉬운 처리방법은 아니다. 이때 간단하게 쓸수있는게 정규 표현식이다.
사용법 코드
#include <iostream>
#include <regex>//regular expression
using namespace std;
int main()
{
//+한개 이상의 문자, * 입력을 안받아도 괜춘
//regex re("\\d+");
//regex re("[ab]");
//regex re("[[:digit:]]{3}");
//regex re("[A-Z]+");
//regex re("[A-Z]{1,5}");
//regex re("[0-9]{1}([-]?)([0-9]{1,4})");
//regex re("(\\w+)(@)(\\w+)(.com)");
regex re("(01)([[:digit:]]{8,9})");
string str;
while (true)
{
getline(cin, str);
if (regex_match(str, re))
cout << "Math" << endl;
else
cout << "No match" << endl;
//print matches
{
auto begin = sregex_iterator(str.begin(), str.end(), re);
auto end = sregex_iterator();
for (auto itr = begin; itr != end; itr++)
{
smatch match = *itr;
cout << match.str() << " ";
}
cout << endl;
}
cout << endl;
}
return 0;
}
자세한 내용은 cplusplus에서 확인할것.
https://www.cplusplus.com/reference/regex/ECMAScript/
ECMAScript syntax - C++ Reference
참조
홍정모의 따라하며 배우는 c++ 강의