2011-01-24 5 views
10

区切り文字としてスペースに基づいて、以下のような文字列を分割する必要があります。しかし、見積もり内のスペースはすべて保存する必要があります。引用符を保持する正規表現分割文字列

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

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

私はCシャープでこれを行うにしようとしています、私はこの正規表現があります:SOで別のポストから@"(?<="")|\w[\w\s]*(?="")|\w+|""[\w\s]*"""を、

research 
library 
"not available" 
author 
"Bernard Shaw" 

に文字列を分割しています残念ながら私の正確な要件を満たしていません。

私はRegexを探しています、それはそのトリックを行うでしょう。

助けてください。

答えて

25

は限りがないがことができるように引用符で囲まれた文字列内で引用され、次のように動作するはずエスケープ:

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 
+0

それにドット、疑問符、exclamaスペースの代わりに記号などを使用します。私は引用符の中を除いてすべての文を一つずつ取得しようとしています。たとえば、歩いた。 **元に戻った。**しかし、なぜ? **そして、 "こんにちは世界。残念ながら** – ErTR

+1

@Ertürköztürk:それは独自のStackOverflow質問に値する - コメントでは答えがあまりにも大きすぎる。 –

+1

@TimPietzckerよく私はなぜわからないが、私はほぼ同じ質問(http://stackoverflow.com/questions/33886103/how-to-find-recurring-word-groups-in-text-with-c)と私はあまりにも多くの反応を持っている "ここではコードライティングサービスではない"または "それは明確ではない"のでコメントで私のチャンスを試している。 – ErTR

3

をここに行く:

C#:

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

正規表現:分割する方法

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

ちょっと、ティムの答えに気付かなかった。それは分裂のために働くでしょう、これは一致のためです。 –

+0

ありがとうJivlain、マッチングのためにも完璧に動作します。 – itsbalur

関連する問題