본문 바로가기

알고리즘

정규표현식(regex) 정리.

정규표현식

정규표현식에 쓰이는 규칙.

(?:...) : ?????!!! 위 규칙의 대부분이 이해가 가지만 이해가 가지 않아 설명을 하겠습니다.

설명에는 (non-capturing) 이라고 되어있습니다.

물음표를 넣지 않고 그냥 (abc) 라는 그룹을 만든다면, 맨마지막에 String Replacement: $n 을 통해 n 번째 그룹에 있는 글자를 가지고 올 수 있습니다.

하지만, (?:...) 을 통해 그룹을 만들게 되면 $n을 통해 글자를 가져올 수 없지만 그만큼 메모리를 아끼게 되는 효과가 있습니다.

가장 많이 쓰이는 정규 표현식 4가지

1. regex_match: 문자열 전체가 정규 표현식에 맞는 지 확인.
간단한 예시 입니다.

#include <iostream>
#include <regex>

using namespace std;

int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    string s="d1w2o3r4d5d6w7o8r9d0";
    regex re("([a-z][0-9])+");
    cout<<(regex_match(s,re)?"True":"False");
    return 0;
}

결과 : True

2. regex_search: 문자열 내에 정규 표현식에 맞는것이 하나라도 있는 경우.

#include <iostream>
#include <regex>

using namespace std;

int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    string s1="word dword", s2="dwordword";
    regex re("^dword");
    smatch m;
    cout<<(regex_search(s1,m,re)?"True":"False")<<','<<(regex_search(s2,m,re)?"True":"False");
    return 0;
}

정규 표현식에 ^ 가 들어가 있기 때문에 스트링이 반드시 d로 시작해야 합니다.

결과 : False,True

3.regex_replace: 문자열 내에 정규 표현식에 맞는 것을 원하는 글자로 바꾸는 경우.

#include <iostream>
#include <regex>

using namespace std;

int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    string s="Hello wolrd!", result;
    regex re("o");
    cout<<regex_replace(s,re,"");
    return 0;
}

결과 : Hell wlrd!

그룹을 만들어서 그룹 끼리 바꾸는 방법.

#include <iostream>
#include <regex>

using namespace std;

int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    string s="hello wolrd", result;
    regex re("([a-z]+) ([a-z]+)");
    cout<<regex_replace(s,re,"$2 $1");
    return 0;
}

결과 : world hello

4. regex_search, sregex_iterator: 문자열 내에 정규 표현식에 맞는단어 여러개를 찾는 경우.

#include <iostream>
#include <regex>

using namespace std;

int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    string s1="dwordword", s2="dworddword";
    regex re("dword");
    smatch m;
    while(regex_search(s1,m,re)){
        cout<<*m.begin()<<',';
        s1=m.suffix().str();
    }
    cout<<'\n';
    while(regex_search(s2,m,re)){
        cout<<*m.begin()<<',';
        s2=m.suffix().str();
    }
    return 0;
}

정답은 같은 sregex_iterator를 이용하는 방법입니다.

#include <iostream>
#include <regex>

using namespace std;

int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    string s1="dwordword", s2="dworddword";
    regex re("dword");

    for(auto it=sregex_iterator(s1.begin(),s1.end(),re);it!=sregex_iterator();it++)
        cout<<*it->begin()<<',';
    cout<<'\n';
    for(auto it=sregex_iterator(s2.begin(),s2.end(),re);it!=sregex_iterator();it++)
        cout<<*it->begin()<<',';
    return 0;
}

결과:
dword,
dword,dword,