我正在寻找一种方法来分割像“StringBuilder SB = new StringBuilder();”这样的刺痛。进入一个单独的单词,符号和空格的数组
var string = "StringBuilder SB = new StringBuilder();";
var array = string.split(...);
输出应该是:
array = ["StringBuilder", " ", "SB", " ", "=", " ", "new", " ", "StringBuilder", "(", ")", ";"];
答案 0 :(得分:4)
不确定这是否符合您的所有需求:
"StringBuilder SB = new StringBuilder();".match(/(\s+|\w+|.)/g);
["StringBuilder", " ", "SB", " ", "=", " ", "new", " ", "StringBuilder", "(", ")", ";"]
答案 1 :(得分:1)
易于定制的解决方案:
function mySplit(str) {
function isChar(ch) {
return ch.match(/[a-z]/i);
}
var i;
var result = [];
var buffer = "";
var current;
var onWord = false;
for (i = 0; i < str.length; ++i) {
current = str[i];
if (isChar(current)) {
buffer += current;
onWord = true;
} else {
if (onWord) {
result.push(buffer);
}
result.push(current);
onWord = false;
}
}
if(onWord) {
result.push(buffer);
}
return result;
}