【问题标题】:Regex split string preserving quotes正则表达式拆分字符串保留引号
【发布时间】:2011-01-24 10:03:07
【问题描述】:

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

research library "not available" author:"Bernard Shaw"

research
library
"not available"
author:"Bernard Shaw"

我正在尝试在 C Sharp 中执行此操作,我有这个正则表达式:@"(?<="")|\w[\w\s]*(?="")|\w+|""[\w\s]*""" 来自 SO 中的另一篇文章,它将字符串拆分为

research
library
"not available"
author
"Bernard Shaw"

很遗憾,这不符合我的确切要求。

我正在寻找任何可以解决问题的正则表达式。

任何帮助表示赞赏。

【问题讨论】:

    标签: c# regex split


    【解决方案1】:

    只要在带引号的字符串中不能有转义的引号,以下应该可以工作:

    splitArray = Regex.Split(subjectString, "(?<=^[^\"]*(?:\"[^\"]*\"[^\"]*)*) (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
    

    此正则表达式仅在空格字符前面和后面都有偶数个引号时才拆分它们。

    没有所有转义引号的正则表达式,解释:

    (?<=      # Assert that it's possible to match this before the current position (positive lookbehind):
     ^        # The start of the string
     [^"]*    # Any number of non-quote characters
     (?:      # Match the following group...
      "[^"]*  # a quote, followed by any number of non-quote characters
      "[^"]*  # the same
     )*       # ...zero or more times (so 0, 2, 4, ... quotes will match)
    )         # End of lookbehind assertion.
    [ ]       # Match a space
    (?=       # Assert that it's possible to match this after the current position (positive lookahead):
     (?:      # Match the following group...
      [^"]*"  # see above
      [^"]*"  # see above
     )*       # ...zero or more times.
     [^"]*    # Match any number of non-quote characters
     $        # Match the end of the string
    )         # End of lookahead assertion
    

    【讨论】:

    • 如何用点、问号、感叹号等而不是空格来分割它。我试图一个接一个地得到每个句子,除了引号内。例如:走过。 转身。但是为什么呢? 然后说:“你好,世界。该死的字符串分裂!”没有羞耻。
    • @ErtürkÖztürk:这值得自己提出 StackOverflow 问题 - 太大,无法在评论中回答。
    • @TimPietzcker 好吧,我不知道为什么,但我问了几乎相同的问题 (stackoverflow.com/questions/33886103/…),我得到了太多的反应,比如“这不是代码编写服务”或“不清楚”所以我在 cmets 尝试我的机会。
    【解决方案2】:

    给你:

    C#:

    Regex.Matches(subject, @"([^\s]*""[^""]+""[^\s]*)|\w+")
    

    正则表达式:

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

    【讨论】:

    • 呵呵,没注意到蒂姆的回答。这将用于拆分,这是用于匹配。
    猜你喜欢
    • 1970-01-01
    • 2014-11-22
    • 2011-02-24
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多