且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按空格拆分字符串,保留带引号的段,允许转义引号

更新时间:2023-01-14 21:18:36

您可以将正则表达式更改为:

You can change your regex to:

keywords = keywords.match(/\w+|"(?:\\"|[^"])+"/g);

而不是 [^] + 你有(?:\\| [^])+ 允许 \或其他角色,但不是未转义的引用。

Instead of [^"]+ you've got (?:\\"|[^"])+ which allows \" or other character, but not an unescaped quote.

一个重要的注意事项是,如果你想让字符串包含一个文字斜杠,它应该是b e:

One important note is that if you want the string to include a literal slash, it should be:

keywords = 'pop rock "hard rock" "\\"dream\\" pop"'; //note the escaped slashes.

此外, \w + $ c $之间存在轻微的不一致c>和 [^] + - 例如,它将匹配单词ab * d,但不是 ab * d (没有引号)。考虑使用 [^\ s] + 代替,这将匹配非空格。

Also, there's a slight inconsistency between \w+ and [^"]+ - for example, it will match the word "ab*d", but not ab*d (without quotes). Consider using [^"\s]+ instead, that will match non-spaces.