javascript正则表达式匹配
我需要根据空格作为分隔符来拆分如下所示的字符串。但引号内的任何空格都应保留。有两种情况需要工作,
情况 1
research library "not available" author:"Bernard Shaw"
到
research
library
"not available"
author:"Bernard Shaw"
情况 2
research library "not available" author:Bernard
,
research
library
"not available"
author:Bernard
我正在尝试使用 Javascript 和正则表达式来完成此操作。
var splitArray = query_string.match(/([^\s]*\"[^\"]+\")|\w+/g);
情况 1 按要求工作,但情况 2 产生如下结果,
research
library
"not available"
author
Bernard
我需要这两种情况都与一个正则表达式一起使用。任何想法表示赞赏。
I need to split a string like the one below, based on space as the delimiter. But any space within a quote should be preserved. There are two cases which needs to work
Case 1
research library "not available" author:"Bernard Shaw"
to
research
library
"not available"
author:"Bernard Shaw"
Case 2
research library "not available" author:Bernard
to
research
library
"not available"
author:Bernard
I am trying to do this with Javascript and regular expression.
var splitArray = query_string.match(/([^\s]*\"[^\"]+\")|\w+/g);
Case 1 works as required but Case 2 produces the result as below
research
library
"not available"
author
Bernard
I need both the cases to work with one Regex. Any ideas appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
说明:
假设带引号的字符串中没有转义引号。
Explanation:
Assuming that there are no escaped quotes within quoted strings.
我在这里测试了这个正则表达式: rubular
更新:
您可能需要添加更多标点符号,例如
;
,
.
?
!
例如研究图书馆! “不可用”作者:“萧伯纳”测试1,测试2;测试2!
I've tested this regex here: rubular
update:
you may want to include some more punctuation marks like
;
,
.
?
!
e.g. research library! "not available" author:"Bernard Shaw" test1, test2; test2!
这至少适用于您的两种情况:
请参阅此处
This works, at least for your two cases:
see here