2011-09-05 6 views
10

부스트 정규 표현식을 사용하여 텍스트 파일에서 서브 래칭을 추출하려고합니다. 현재 유효한 전자 메일 주소 대신 첫 번째 유효한 줄과 전체 줄만 반환합니다. 나는 이터레이터를 사용하고 서브 미팅을 시도했지만 성공하지 못했다. 다음은 현재 코드입니다.부스트 정규식을 C++로 사용하여 서브 어셈블리 추출

if(Myfile.is_open()) { 
    boost::regex pattern("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$"); 
    while(getline(Myfile, line)) { 
      string::const_iterator start = line.begin(); 
      string::const_iterator end = line.end(); 
      boost::sregex_token_iterator i(start, end, pattern); 
      boost::sregex_token_iterator j; 
      while (i != j) { 
      cout << *i++ << endl; 

    } 
    Myfile.close(); 
} 

답변

16

boost::smatch을 사용하십시오.

boost::regex pattern("what(ever) ..."); 
boost::smatch result; 
if (boost::regex_search(s, result, pattern)) { 
    string submatch(result[1].first, result[1].second); 
    // Do whatever ... 
} 
+0

아마 내 Regex가 잘못되었지만 적절한 결과를 얻을 수 없습니다. – John

+0

감사합니다, 감사합니다. – John

13
const string pattern = "(abc)(def)"; 
const string target = "abcdef"; 

boost::regex regexPattern(pattern, boost::regex::extended); 
boost::smatch what; 

bool isMatchFound = boost::regex_match(target, what, regexPattern); 
if (isMatchFound) 
{ 
    for (unsigned int i=0; i < what.size(); i++) 
    { 
     cout << "WHAT " << i << " " << what[i] << endl; 
    } 
} 

출력은 다음과

WHAT 0 abcdef 
WHAT 1 abc 
WHAT 2 def 

부스트 괄호 submatches를 사용하고, 첫 번째 submatch는 항상 완전 일치하는 문자열입니다. regex_match는 전체 입력 행을 패턴과 일치시켜야합니다. 부분 문자열을 일치시키려는 경우 대신 regex_search를 사용하십시오.

위 예제에서는 boost :: regex :: extended 매개 변수를 사용하여 지정하는 posix 확장 정규식 구문을 사용합니다. 이 매개 변수를 생략하면 perl 스타일 정규식 구문을 사용하는 구문이 변경됩니다. 다른 정규식 구문을 사용할 수 있습니다.

관련 문제