用规则javascript拆分

时间:2014-09-18 21:41:32

标签: javascript coffeescript

我希望能够用空格分割字符串,但如果空格在引号或括号之间则不能。

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

我希望它输出为:

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

3 个答案:

答案 0 :(得分: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)
*/

答案 1 :(得分:0)

我想有一种更简单的方法,但我写了一个小函数。



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

答案 2 :(得分:0)

这可能不是很花哨,但它可以完成这项工作。我还没有在大型套装上测试它,但它适用于你的例子。

&#13;
&#13;
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) {
              	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, ['"','('], ['"',')']));
&#13;
&#13;
&#13;