【问题标题】:javascript regular expression matchjavascript正则表达式匹配
【发布时间】:2011-02-07 14:17:24
【问题描述】:

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

案例一

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 

我需要这两种情况才能使用一个正则表达式。任何想法表示赞赏。

【问题讨论】:

    标签: javascript regex match


    【解决方案1】:
    [^"\s]+(?:"[^"]+")?|"[^"]+"
    

    解释:

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

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

    【讨论】:

    • 谢谢蒂姆。它工作得很好。在我看来是所有答案中最全面的。
    【解决方案2】:
    ([^\s]*\"[^\"]+\")|\w+:?
    

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

    更新: 您可能希望包含更多标点符号,例如 ; , . ? !
    例如研究图书馆! “不可用”作者:“伯纳德·肖”test1,test2;测试2!

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

    【讨论】:

    • 谢谢。当我尝试使用它时,它会分别给出“作者:”和“伯纳德”。不过,在 Rubular 中似乎效果很好。
    【解决方案3】:

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

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

    see here

    【讨论】:

      猜你喜欢
      • 2011-11-29
      • 2012-09-22
      • 1970-01-01
      • 2011-02-19
      • 2017-03-04
      • 2015-11-13
      相关资源
      最近更新 更多