我有一个字符串:
'"Apples" AND "Bananas" OR "Gala Melon"'
我想把它转换成一个数组
arr = ['"Apples"', 'AND', '"Bananas"', 'OR', '"Gala Melon"']
我不知道我是否可以用正则表达式来做。我开始认为我可能必须一次解析每个字符以匹配双引号。
最佳答案
input = '"Apples" AND "Bananas" OR "Gala Melon"'
output = input.match(/\w+|"[^"]+"/g)
// output = ['"Apples"', 'AND', '"Bananas"', 'OR', '"Gala Melon"']
正则表达式的解释:
/
- 正则表达式的开始
\w+
- 单词字符序列
|
- 或
"[^"]+"
- 任何引用(假设没有转义引号)
/g
- 正则表达式结束,全局标志(执行多个匹配)
关于javascript - 如何在 Javascript 中标记字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14853404/