regular expression
matching text
- 원하는 글자를 찾을 때
- regex re("hello");
alternation
- 여러 개 중에 하나를 찾을 때
- regex re("Fred|Wilma|Tom");
alternation & grouping
- 선택적으로 구한것과 뒤 단어는 exact match 를 구함
- regex ex("(Fred|tom)son");
-> Fredson 또는 tomson 을 찾아 줌
single character
- [] 를 사용함
- regex ex("[0-9]"); // 0부터 9사이의 한 숫자
- regex ex("[a-zA-Z0-9.]"); // 영문자 또는 숫자 또는 점 중에 하나
match quantifiers
- + : 하나 이상 존재
- ? : 없거나 하나
- * : 0개 이상
match quantifier
- {min number, max number}
- regex ex("[0-9]{1,3}"); // 숫자가 1~3개
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int parseInfo(string s, regex rule)
{
sregex_token_iterator it(s.begin(), s.end(), rule, -1);
sregex_token_iterator reg_end;
string cmd;
int c = 0;
for(; it != reg_end; ++it) {
if (c == 0) {
cmd = string(it->str());
}
cout << "[" << c++ << "] " << it->str() << endl;
}
cout << "command:" << cmd << endl;
return 0;
}
int main()
{
//regex rule("\\w+:");
//regex rule("\n");
regex rule("\n|:|/");
// std::smatch m;
// if(std::regex_search(s, m, rule)) {
// cout << "found match:" << s << endl;
// }
string s1("cmd1\n");
string s2("cmd2:abc\n");
string s3("cmd3/tree\n");
parseInfo(s1, rule);
parseInfo(s2, rule);
parseInfo(s3, rule);
return 0;
}
컴파일
root@cnode01-m:~/temp/re# g++ test.cc -std=c++11
root@cnode01-m:~/temp/re# ./a.out
[0] cmd1
command:cmd1
[0] cmd2
[1] abc
command:cmd2
[0] cmd3
[1] tree
command:cmd3