컴퓨터/miscellaneous

Regular Expression

Hikasiru 2006. 8. 24. 10:51

Perl, Java, C#은 언어 자체에서 정규표현식을 지원하지만 C++에선 -_ -

boost의 정규표현식을 사용하자.
예제. http://network.hanbitbook.co.kr/view.php?bi_id=1218

Unicode 와 ICU 지원.
http://icu.sourceforge.net/

bjam -sICU_PATH=c:\boost\icu -sICU_LINK=c:\boost\icu\lib -sTOOLS=vc-7_1 install


좋은 토크나이저
http://www.linuxselfhelp.com/HOWTO/C++Programming-HOWTO-7.html

예제.

간단한 예제를 하나 들면.(유니코드 지원입니다. ICU 설치 안함)


'\n'을 기준으로 토큰화를 하는 함수

void Tokenize(const wstring& str,
             deque<wstring>& tokens,
             const wstring& delimiters = L"\n")
{
   // Skip delimiters at beginning.
   wstring::size_type lastPos = str.find_first_not_of(delimiters, 0);
   // Find first "non-delimiter".
   wstring::size_type pos     = str.find_first_of(delimiters, lastPos);

   while (wstring::npos != pos || wstring::npos != lastPos)
   {
       // Found a token, add it to the vector.
       tokens.push_back(str.substr(lastPos, pos - lastPos));
       // Skip delimiters.  Note the "not_of"
       lastPos = str.find_first_not_of(delimiters, pos);
       // Find next "non-delimiter"
       pos = str.find_first_of(delimiters, lastPos);
   }
}

std::wstring log;
boost::wregex re;
boost::wcmatch matches;

deque<wstring> tokens;

Tokenize(log, tokens); //(log에 문자열이 들어갑니다)

re = L"여기에 정규표현식";

while ( tokens.size() > 0 ) // 토큰이 남아있으면
{

 if ( boost::regex_match(tokens.front().c_str(), matches, re)) // 정규표현식과 match가 된다면
 {
   for ( unsigned column=1; column <matches.size(); column++ ) // match가 남아있는 동안
  {
     wstring match(matches[column].first, matches[column].second);

     wcout << match << endl; // 출력합니다.

   }//for

 }//if

  tokens.pop_front(); // tokens에서 맨 앞을 하나씩 pop(제거)합니다.

}//while