Che*_*hev 5 javascript regex arrays string split
最终我试图改变这个:
var msg = '-m "this is a message" --echo "another message" test arg';
Run Code Online (Sandbox Code Playgroud)
进入这个:
[
'-m',
'this is a message',
'--echo',
'another message',
'test',
'arg'
]
Run Code Online (Sandbox Code Playgroud)
我不太确定如何解析字符串以获得所需的结果.这是我到目前为止:
var msg = '-m "this is a message" --echo "another message" test arg';
// remove spaces from all quoted strings.
msg = msg.replace(/"[^"]*"/g, function (match) {
return match.replace(/ /g, '{space}');
});
// Now turn it into an array.
var msgArray = msg.split(' ').forEach(function (item) {
item = item.replace('{space}', ' ');
});
Run Code Online (Sandbox Code Playgroud)
我认为这样可行,但是人类看起来像是一种变幻无常的向后完成我想要的方式.我相信你们比分割前创建一个占位符字符串要好得多.
使用exec(),你可以在没有引号的情况下获取字符串:
var test="once \"upon a time\" there was a \"monster\" blue";
function parseString(str) {
var re = /(?:")([^"]+)(?:")|([^\s"]+)(?=\s+|$)/g;
var res=[], arr=null;
while (arr = re.exec(str)) { res.push(arr[1] ? arr[1] : arr[0]); }
return res;
}
var parseRes= parseString(test);
// parseRes now contains what you seek
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1589 次 |
| 最近记录: |