gpt4 book ai didi

javascript - 如何将字符串中每个引用的句子放入数组(javascript)

转载 作者:行者123 更新时间:2023-12-04 00:52:25 27 4
gpt4 key购买 nike

我有一个看起来像这样的字符串:

var message = '"this is a question" "answer one" "answer two" "answer three"';

我希望字符串引号内的每个句子都在这样的数组中:

array = ["this is a question", "answer one", "answer two", "answer three"];

我如何在 JavaScript 中实现这一点?谢谢。

最佳答案

你试过 str.split() 了吗?

const array = message.split(/\s(?=")/);
//This regex searches for a space, but makes sure it has a " after it.

文档: https://www.w3schools.com/jsref/jsref_split.asp

以防万一你想分解正则表达式:

/ start of regex
\s escaped character: whitespace
(?= start of positive lookahead
" literal character: quotation mark
) end of positive lookahead
/ end of regex

编辑:Oskar Grosser 在评论中说,有时这行不通。这是对此的修复:

/(?<=[^\\]?")\s+(?=")/

分割:

/ start of regex
(?<= start of positive lookbehind
[^ start of negated charset (in case there was any \"s)
\\ escaped literal character: backslash (\)
] end of negated charset
? quantifier: 0 or 1 (in case it was at the beginning)
" literal character: quotation mark (")
) end of positive lookbehind
\s escaped character: whitespace
+ quantifier: 1 or more (for in case there was 2 whitespace instead of 1)
(?= start of positive lookahead
" literal character: quotation mark (")
) end of positive lookahead
/ end of regex

请注意,lookbehinds 在某些浏览器上有效,但并非在所有浏览器上都有效。

关于javascript - 如何将字符串中每个引用的句子放入数组(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65515542/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com