2013-04-02 2 views
1

모든 ';'을 찾는 정규 표현식을 작성하려고합니다. 새 줄 (\ n) 문자 뒤에 오는 문자.LookBehind 기능이없는 정규 표현식

;(?!\\\n) 

및 ';' 문자 :

(?< !;)\\\n 

불행하게도 내가 Qt는 4.7.4 QRegExp를 사용하고 그것을 "뒤에 봐"지원하지 않습니다. 위의 정규식을 다시 작성하여 "Look Behind"를 사용하지 않으려면 어떻게해야합니까? 문서에서 인용

답변

1

:

http://doc.qt.digia.com/4.7/qregexp.html#details

모두 제로 폭 포지티브 제로 폭 부정적 예측 주장 (? = 패턴) 및 (?! 패턴) 동일한 구문 등으로 지원 펄. 아마 무슨 일이 일어나고 무엇

는 단지 \n 대신 \r\n를 삽입 ... 또는 어쩌면 그것은 윈도우 머신에서 생성 된 텍스트 파일이었다 한 Windows 시스템에서 실행되는 것입니다.

내가주의 깊게 알아 낸 점은, 대부분의 정규 표현식 처리기로 가변 길이 lookbehind를 가질 수 없다는 것입니다.

하면 lookbehinds/lookaheads은 여전히 ​​가지고있는 문서의 code-examples section에서 당신에게 문제가 캡처 그룹을 사용하고 조사하고 관심있는 캡처 그룹 만 참조 할 수있는 다른 옵션을 선택합니다.

을주고있다 이 :

캡쳐 그룹이 괄호로 정의하고 (1)의 제로 번째 인덱스를 시작 인덱스에 의해 나중에 액세스 전체 경기 (캡처 그룹으로 나누어되지 않음)입니다입니다
str = "Nokia Corporation\tqt.nokia.com\tNorway"; 
QString company, web, country; 
rx.setPattern("^([^\t]+)\t([^\t]+)\t([^\t]+)$"); 
if (rx.indexIn(str) != -1) { 
    company = rx.cap(1); 
    web = rx.cap(2); 
    country = rx.cap(3); 
} 

.

http://doc.qt.digia.com/4.7/qregexp.html#cap

http://doc.qt.digia.com/4.7/qregexp.html#capturedTexts

희망하는 데 도움이. 정규 표현식은 올바르게 작동 할 때 많은 즐거움을 줄 수 있습니다. 행운을 빕니다.

나는 tool을 사용하는 것을 좋아합니다. 형식 지정은 QRegEx와 약간 다를 수 있지만 일단 번역하면 테스트하고 테스트하는 것이 빠릅니다. UPDATE

:

#include <QCoreApplication> 
#include <QRegExp> 
#include <QString> 
#include <QDebug> 
#include <QStringList> 

int main(int argc, char *argv[]) 
{ 
    QCoreApplication a(argc, argv); 

    QString str = 
      "This is a long string;\n" 
      "with some semi colons;\n" 
      "sometimes followed by a new line;\n" 
      "and other times followed; by something else.\n" 

      "(;)([^\\n]) find a semicolon and a new line\n" 
      "(;)(?!\\n) find a semicolon not followed by a new line, negative look-ahead\n" 

      "([^;])(\\n) find a non semicolon and a new line\n" 
      "(?<!;)(\\n) find a new line, not preceeded by a semicolon.\n"; 

    QList <QRegExp> rx_list; 

    QRegExp rx_colon_and_non_newline; 
    rx_colon_and_non_newline.setPattern("(;)([^\\n])"); 

    QRegExp rx_colon_and_neg_lookahead; 
    rx_colon_and_neg_lookahead.setPattern("(;)(?!\\n)"); 

    QRegExp rx_non_colon_and_newline; 
    rx_non_colon_and_newline.setPattern("([^;])(\\n)"); 

    QRegExp rx_neg_lookbehind_and_newline; 
    rx_neg_lookbehind_and_newline.setPattern("(?<!;)(\\n)"); 

    rx_list << rx_colon_and_non_newline 
      << rx_colon_and_neg_lookahead 
      << rx_non_colon_and_newline 
      << rx_neg_lookbehind_and_newline; 

    foreach(QRegExp rx, rx_list) 
    { 
     int count = 0; 
     int pos = 0; 
     qDebug() << "Pattern" << rx.pattern(); 
     while ((pos = rx.indexIn(str, pos)) != -1) { 
      QStringList capturedTexts(rx.capturedTexts()); 

      for(int i = 0; i<capturedTexts.size(); i++) 
       capturedTexts[i].replace('\n',"\\n"); 

      qDebug() << "\t" << count << "Found at position" << pos << capturedTexts; 
      // qDebug() << rx.cap(); 
      pos += rx.matchedLength(); 
      ++count; 
     } 
     if(count == 0) 
      qDebug() << "\tNo matches found."; 
    } 


    return a.exec(); 
} 

출력 :

궁금
Pattern "(;)([^\n])" 
     0 Found at position 104 ("; ", ";", " ") 
     1 Found at position 126 (";)", ";", ")") 
     2 Found at position 169 (";)", ";", ")") 
     3 Found at position 247 (";]", ";", "]") 
     4 Found at position 295 (";)", ";", ")") 
Pattern "(;)(?!\n)" 
     0 Found at position 104 (";", ";") 
     1 Found at position 126 (";", ";") 
     2 Found at position 169 (";", ";") 
     3 Found at position 247 (";", ";") 
     4 Found at position 295 (";", ";") 
Pattern "([^;])(\n)" 
     0 Found at position 123 (".\n", ".", "\n") 
     1 Found at position 166 ("e\n", "e", "\n") 
     2 Found at position 242 ("d\n", "d", "\n") 
     3 Found at position 289 ("e\n", "e", "\n") 
     4 Found at position 347 (".\n", ".", "\n") 
Pattern "(?<!;)(\n)" 
     No matches found. 
+0

,이 답변이 안 여기 4 가지 캡처 문자열과 그들이 QRegEx으로 발견을 보여주는, 전체 모음입니다 받아 들였다. 나는 캡쳐 그룹을 사용하는 것이 내 의견으로는 보이지 않는 것을 사용하는 것보다 낫다고 동의한다.내가 LA/LB를 사용하는 진정한 유일한 이유는 명령 줄에서 grep을 처리 할 때 신속하게 뭔가를 필터링해야 할 때입니다. 그리고 때때로 GREP 또는 SED로 스크립팅 할 때 사용하는 것 외에는 사용하지 않는 것 이외에도 그 시점에서 Perl을 사용하면 더 이상 캡처를 사용하지 않아도됩니다. 부정적인 look-behinds는 고정 된 길이 여야하기 때문에 어쨌든 빨기도합니다. 문자열이 얼마나 길어질 지 정확히 알지 못할 때 짜증이납니다! – osirisgothra

+0

가변 길이 룩 - 배후 (variable-length look-behind)를 사용할 수 없다는 사실을 처음 알게되면 꽤 오랜 시간이 걸렸습니다. 나는 미쳤다고 생각했다. 아마도이 답을 다시 찾아보고 어떻게해야 하는지를 보여주는 완전한 테스트와 해결책을 제시해야 할 것입니다. 주제에 대한 내 대답은 다음과 같습니다. http://stackoverflow.com/search?q=user%3A999943+qregex – phyatt