保留引号的正则表达式拆分字符串

13

我需要根据空格作为分隔符,拆分以下类似的字符串。但是引号内的所有空格都应该被保留。

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

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

我正在尝试在C#中完成这个任务,我有一个来自Stack Overflow的正则表达式:@"(?<="")|\w[\w\s]*(?="")|\w+|""[\w\s]*""",它可以将字符串分割成

research
library
"not available"
author
"Bernard Shaw"
很不幸,这并不能完全满足我的需求。
我正在寻找任何可以解决问题的正则表达式。
感谢任何帮助。
2个回答

33
只要在引号内部不存在可转义的引号,以下内容应该可以正常工作:
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

如何使用句点、问号、感叹号等符号而非空格来分割它。我想逐句获取每个句子,但不包括引号内的内容。例如:走了。回头看了看。但为什么?然后说:“你好世界。该死的字符串分割!”毫不羞愧。 - ErTR
1
@ErtürkÖztürk:这个问题值得在StackOverflow上单独提问,因为它太大了,无法在评论中回答。 - Tim Pietzcker
2
@TimPietzcker,我不知道为什么,但我几乎问了同样的问题(https://dev59.com/3ZHea4cB1Zd3GeqPomQE),但我得到了太多的反应,比如“这里不是代码编写服务”或“不清楚”,所以我在评论中尝试一下我的运气。 - ErTR

3

请看下面:

C#:

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

正则表达式:

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

嘿,没注意到Tim的回答。那个可以用来分割,这个是用来匹配的。 - Joel Rein

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接