2011-12-25 2 views
0

문자열이 있는데 구조 블록에있는 문자열을 파싱하고 싶습니다.구조화 된 형식을 구문 분석하는 방법은 무엇입니까?

그래서,이 같은 문자열의 구조 :

if(true) { 
    if(true) { 
     if(true) {} 
    } 
} 
if(true) { 
    if(true) { 
     if(true) {} 
    } 
} 

그리고이 같은 부모 블록에 하나의 분할 싶습니다

if(true) { 
    if(true) { 
     if(true) {} 
    } 
}, 

if(true) { 
    if(true) { 
     if(true) {} 
    } 
} 

내 코드 :

string condition = 
"if(true) {\ 
    if(true) {\ 
     if(true) {}\ 
    }\ 
}\ 
if(true) {\ 
    if(true) {\ 
     if(true) {}\ 
    }\ 
}"; 

string item; 
stringstream stream(condition); 
vector<string> array; 

//splitting on sections 
while (getline(stream, item, '}')) { 
    array.push_back(item + "}"); 
} 

for(int i = 0; i < array.size(); i++) { 
    cout << i << array[i] << endl; 
} 

검색 결과 :

0 if(true) { if(true) { if(true) {} 
1 } 
2 } 
3 if(true) { if(true) { if(true) {} 
4 } 
5 } 

그러나 필요 :

0 if(true) { if(true) { if(true) {} } } 
1 if(true) { if(true) { if(true) {} } } 

어떻게 감지하고 더 정확하게 부모 블록을 구문 분석 또는 알고리즘을 말해?

+0

보인다? 그것이 사실이라면 몇 가지 해결책을 살펴보십시오. http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c –

+0

감사합니다. 이미 해당 게시물을 보았지만 약간 다른 문제. 구문 분석 할 알고리즘을 이해하지 못합니다. –

+0

@AlexanderGuiness : 일부 고급 기능 파싱을 위해 Boost.Spirit을 살펴볼 수 있습니다. – GManNickG

답변

2

현재 깊이를 유지해야합니다. 가장 좋은 파서가 반복자 기반이라는 것을 알았으니 여기에 나와 있습니다. std::getline은 매우 간단한 형식을 제외하고는 파싱에별로 유용하지 않습니다.

완전히 테스트되지 않은 코드는 : 당신이 문자열을 분할 할 같은

std::vector<std::string> vec; 

int depth = 0; 
std::string::const_iterator first = condition.begin(), 
          last = condition.end(), 
          iter = first; 

for(;;) 
{ 
    iter = std::find_if(iter, last, 
         [](char ch) { return ch == '{' || ch == '}'; }); 

    if(iter == last) 
    { 
     if(depth) 
     { 
      throw std::runtime_error("unclosed block found."); 
     } 

     break; 
    } 

    if(*iter == '{') 
    { 
     ++depth; 
     ++iter; 
    } 
    else if(*iter == '}' && !--depth) 
    { 
     v.push_back(std::string(first, ++iter)); 
     first = iter; 
    } 
    else 
    { 
     ++iter; 
    } 
} 
관련 문제