javascript正则表达式匹配

发布于 2024-10-16 12:50:27 字数 706 浏览 8 评论 0原文

我需要根据空格作为分隔符来拆分如下所示的字符串。但引号内的任何空格都应保留。有两种情况需要工作,

情况 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

海未深 2024-10-23 12:50:27
[^"\s]+(?:"[^"]+")?|"[^"]+"

说明:

[^"\s]+       # One or more non-space/non-quote characters
(?:"[^"]+")?  # optionally followed by a quoted string
|             # or
"[^"]+"       # just a quoted string.

假设带引号的字符串中没有转义引号。

[^"\s]+(?:"[^"]+")?|"[^"]+"

Explanation:

[^"\s]+       # One or more non-space/non-quote characters
(?:"[^"]+")?  # optionally followed by a quoted string
|             # or
"[^"]+"       # just a quoted string.

Assuming that there are no escaped quotes within quoted strings.

此刻的回忆 2024-10-23 12:50:27
([^\s]*\"[^\"]+\")|\w+:?

我在这里测试了这个正则表达式: rubular

更新:
您可能需要添加更多标点符号,例如 ; , . ? !
例如研究图书馆! “不可用”作者:“萧伯纳”测试1,测试2;测试2!

([^\s]*\"[^\"]+\")|\w+[:;\.,\?!]?
([^\s]*\"[^\"]+\")|\w+:?

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!

([^\s]*\"[^\"]+\")|\w+[:;\.,\?!]?
挽容 2024-10-23 12:50:27

这至少适用于您的两种情况:

((?:[^\s]*\"[^\"]+\")|[\w:]+)

请参阅此处

This works, at least for your two cases:

((?:[^\s]*\"[^\"]+\")|[\w:]+)

see here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文