2011-10-29 7 views
5

의 문자열에 정규식 리터럴이 있습니다. 자바 스크립트 코드의 일종의 파싱을 자바 스크립트와 함께하고 있습니다. 나는이 작업을 수행해야하는 이유의 세부 사항을 아끼지하지만 내가하지이 내 목적을 위해 불필요로, 라이브러리 코드의 거대한 덩어리를 통합하려는 할 말을 충분 그것은 중요하다거야 I 매우 가볍고 비교적 단순하게 유지하십시오. 제발 JsLint 같은 것을 사용하지 말아주세요. 대답이 답안에 붙여 넣을 수있는 것보다 더 많은 코드라면, 아마 내가 원하는 것 이상입니다.자바 스크립트 코드

내 코드는 따옴표 붙은 섹션 및 주석을 검색 한 다음 중괄호, 대괄호 및 괄호 (대괄호와 주석 또는 쉼표로 이스케이프 처리하여 혼동하지 않도록주의)를 잘 수행 할 수 있습니다. . 이것은 내가 그것을 할 필요이며, 한 가지 예외가 ... 잘 수행합니다

그것은 정규 표현식 리터럴 혼동 될 수있다. 그래서 자바 스크립트 문자열에서 정규 표현식 리터럴을 탐지하는 데 도움이되기를 바래서 적절하게 처리 할 수 ​​있습니다. 이 같은

뭔가 :

function getRegExpLiterals (stringOfJavascriptCode) { 
    var output = []; 
    // todo! 
    return output; 
} 

var jsString = "var regexp1 = /abcd/g, regexp1 = /efg/;" 
console.log (getRegExpLiterals (jsString)); 

// should print: 
// [{startIndex: 13, length: 7}, {startIndex: 32, length: 5}] 
+0

정규 표현식 리터럴을 개시할지 여부를 판정

비트? // 당신이 원하는 것을 // 원한다면 // 할 수 있습니다. – FailedDev

+0

정규식 리터럴인지 확인해야하므로 슬래시를 찾는 것은 그렇게하지 않을 것입니다. – rob

답변

5

es5-lexer 또한 분할 표현에서 JS 코드에서 정규 표현식을 구별하는 매우 정확한 추론을 사용하고, JS 렉서는 당신이 만드는 데 사용할 수있는 토큰 레벨 변환을 제공합니다 그 결과 프로그램은 렉서 (lexer)처럼 완전한 JS 파서에 의해 같은 방식으로 해석 될 것이다. / 정규 표현식 guess_is_regexp.js에서 시작되어 검사가 scanner_test.js line 401

var REGEXP_PRECEDER_TOKEN_RE = new RegExp(
    "^(?:" // Match the whole tokens below 
    + "break" 
    + "|case" 
    + "|continue" 
    + "|delete" 
    + "|do" 
    + "|else" 
    + "|finally" 
    + "|in" 
    + "|instanceof" 
    + "|return" 
    + "|throw" 
    + "|try" 
    + "|typeof" 
    + "|void" 
    // Binary operators which cannot be followed by a division operator. 
    + "|[+]" // Match + but not ++. += is handled below. 
    + "|-" // Match - but not --. -= is handled below. 
    + "|[.]" // Match . but not a number with a trailing decimal. 
    + "|[/]" // Match /, but not a regexp. /= is handled below. 
    + "|," // Second binary operand cannot start a division. 
    + "|[*]" // Ditto binary operand. 
    + ")$" 
    // Or match a token that ends with one of the characters below to match 
    // a variety of punctuation tokens. 
    // Some of the single char tokens could go above, but putting them below 
    // allows closure-compiler's regex optimizer to do a better job. 
    // The right column explains why the terminal character to the left can only 
    // precede a regexp. 
    + "|[" 
    + "!" // !   prefix operator operand cannot start with a division 
    + "%" // %   second binary operand cannot start with a division 
    + "&" // &, &&  ditto binary operand 
    + "(" // (   expression cannot start with a division 
    + ":" // :   property value, labelled statement, and operand of ?: 
      //    cannot start with a division 
    + ";" // ;   statement & for condition cannot start with division 
    + "<" // <, <<, << ditto binary operand 
    // !=, !==, %=, &&=, &=, *=, +=, -=, /=, <<=, <=, =, ==, ===, >=, >>=, >>>=, 
    // ^=, |=, ||= 
    // All are binary operands (assignment ops or comparisons) whose right 
    // operand cannot start with a division operator 
    + "=" 
    + ">" // >, >>, >>> ditto binary operand 
    + "?" // ?   expression in ?: cannot start with a division operator 
    + "[" // [   first array value & key expression cannot start with 
      //    a division 
    + "^" //^   ditto binary operand 
    + "{" // {   statement in block and object property key cannot start 
      //    with a division 
    + "|" // |, ||  ditto binary operand 
    + "}" // }   PROBLEMATIC: could be an object literal divided or 
      //    a block. More likely to be start of a statement after 
      //    a block which cannot start with a /. 
    + "~" // ~   ditto binary operand 
    + "]$" 
    // The exclusion of ++ and -- from the above is also problematic. 
    // Both are prefix and postfix operators. 
    // Given that there is rarely a good reason to increment a regular expression 
    // and good reason to have a post-increment operator as the left operand of 
    // a division (x++/y) this pattern treats ++ and -- as division preceders. 
); 
+0

덕분에, 그것은 작품의 인상적인 작품이다. 행복한 렉싱. – rob

+0

@ 롭, 천만에요 (당신은 또한 썼다되는 prettifier, 그리고 내가 광범위하게 사용하고있는 것처럼) 마이크, 내가 아니라 미래에 전체 렉서에 대한 사용을 할 수 있습니다 –