Rem*_*emi 26 javascript regex split
var str = 'single words "fixed string of words"';
var astr = str.split(" "); // need fix
Run Code Online (Sandbox Code Playgroud)
我希望数组如下:单个,单词,固定字符串.
YOU*_*YOU 27
str.match(/\w+|"[^"]+"/g)
//single, words, "fixed string of words"
Run Code Online (Sandbox Code Playgroud)
dal*_*lin 24
接受的答案并不完全正确.它分隔非空格字符,如. - 并在结果中留下引号.执行此操作以便排除引号的更好方法是使用捕获组,如下所示:
//The parenthesis in the regex creates a captured group within the quotes
var myRegexp = /[^\s"]+|"([^"]*)"/gi;
var myString = 'single words "fixed string of words"';
var myArray = [];
do {
//Each call to exec returns the next regex match as an array
var match = myRegexp.exec(myString);
if (match != null)
{
//Index 1 in the array is the captured group if it exists
//Index 0 is the matched text, which we use if no captured group exists
myArray.push(match[1] ? match[1] : match[0]);
}
} while (match != null);
Run Code Online (Sandbox Code Playgroud)
myArray现在将包含OP所要求的内容:
single,words,fixed string of words
Run Code Online (Sandbox Code Playgroud)
Sea*_*sey 12
这使用了分割和正则表达式匹配的混合.
var str = 'single words "fixed string of words"';
var matches = /".+?"/.exec(str);
str = str.replace(/".+?"/, "").replace(/^\s+|\s+$/g, "");
var astr = str.split(" ");
if (matches) {
for (var i = 0; i < matches.length; i++) {
astr.push(matches[i].replace(/"/g, ""));
}
}
Run Code Online (Sandbox Code Playgroud)
这会返回预期的结果,尽管单个正则表达式应该能够完成所有操作.
// ["single", "words", "fixed string of words"]
Run Code Online (Sandbox Code Playgroud)
更新 这是S.Mark提出的方法的改进版本
var str = 'single words "fixed string of words"';
var aStr = str.match(/\w+|"[^"]+"/g), i = aStr.length;
while(i--){
aStr[i] = aStr[i].replace(/"/g,"");
}
// ["single", "words", "fixed string of words"]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20015 次 |
| 最近记录: |