2014-09-18 5 views
0

공백으로 문자열을 나눌 수 있지만 공백이 따옴표 또는 괄호 사이에있는 경우는 제외하고 싶습니다.규칙으로 분할 자바 스크립트

string = 'My str "hello world" (cool str though)'; 

나는대로 출력을 원하는 : 나는 간단한 방법이 생각

['My', 'string', 'hello world', 'cool str though']; 
+0

@elclanrs을 내가 그것을 어떻게 아무 생각이 없다 . 정규식 매개 변수를 사용하여 split 메서드를 사용하고 싶습니다. –

+0

분할하려는 것보다는 보관하고 싶은 것을 보면서 공격 할 수 있습니다. –

+0

@AlexWayne 텍스트가 동적입니다. 나는 이것을하는 방법을 정말로 원했습니다. 하지만 불가능한 것 같습니다. –

답변

1

, 당신은 세트를 일치시킬 수 있습니다 당신이 정의

var rx=/("[^"]+"|\([^(]+\)|[^ ]+)/g, 

s='My str "hello world" (cool str though)'; 

s.match(rx).join('\n') 

/* returned value: (String) 
My 
str 
"hello world" 
(cool str though) 
*/ 
0

,하지만 난 작은 기능을 썼다.

function foo() { 
 
var x = 'My str "hello world" (cool str though)'.split(' '); 
 
\t var newx = []; 
 
\t for (var i=0,k=0;i<x.length;i++,k++){ 
 
\t \t if(x[i].indexOf('"') > -1){ 
 
\t \t \t newx[k] = x[i]; 
 
\t \t \t i++; 
 
\t \t \t while(i<x.length){ 
 
\t \t \t \t newx[k] = newx[k] + ' ' + x[i]; 
 
\t \t \t \t if(x[i].indexOf('"') > -1)break; 
 
\t \t \t \t i++; 
 
\t \t \t } 
 
\t \t \t continue; 
 
\t \t } 
 
\t \t else if(x[i].indexOf('(') > -1){ 
 
\t \t \t newx[k] = x[i]; 
 
\t \t \t i++; 
 
\t \t \t while(i<x.length){ 
 
\t \t \t \t newx[k] = newx[k] + ' ' + x[i]; 
 
\t \t \t \t if(x[i].indexOf(')') > -1)break; 
 
\t \t \t \t i++; 
 
\t \t \t } 
 
\t \t \t continue; 
 
\t \t } 
 
\t \t else newx[k]=x[i]; 
 
\t } 
 
\t alert(newx); 
 
}
<button type="button" onclick="foo()">bar</button>

0

이없는 아주 멋진 될 수 있지만, 작업을 수행합니다. 나는 큰 세트에서 그것을 테스트하지 않았지만 그것은 당신의 예제를 위해 작동합니다. 당신이 탈출하거나 중첩 된 따옴표와 괄호를 사용하지 않는 경우

var strng = 'My str "hello world" (cool str though)'; 
 

 
function split(str, ignore1, ignore2) { 
 
    var result = new Array(); 
 
    var pos = 0; 
 
    var blocked = false; 
 

 
    for (i = 0; i < str.length; i++) { 
 
     console.log("pos: " + pos + ", i:" + i); 
 
     if (blocked) { 
 
      if (str.charAt(i) == blocked) { 
 
       \t result.push(str.substr(pos, i - pos)); 
 
       pos = i + 1; 
 
       blocked = false; 
 
      } 
 
     } else { 
 
      var ignPos = ignore1.indexOf(str.charAt(i)); 
 
      if (ignPos > -1){ 
 
       console.log('blocked: '+str.charAt(i)); 
 
       blocked=ignore2[ignPos]; 
 
       pos = i + 1; 
 
      } else if (str.charAt(i) == " ") { 
 
       console.log('found'); 
 
       if (i==pos+1 || i==pos) { 
 
        pos = pos + 1; 
 
       } else { 
 
        result.push(str.substr(pos, i - pos)); 
 
        pos = i + 1; 
 
       } 
 
      } 
 
     } 
 
    } 
 
    if (pos!=str.length){result.push(str.substr(pos, i - pos))}; 
 
    return result; 
 
} 
 

 
console.log(split(strng, ['"','('], ['"',')']));

관련 문제