現在、次の入力でテキストを一致させてキャプチャしようとしています:
field: one two three field: "moo cow" field: +this
と一致させることはできますが、コンテンツの残りの部分と一致field:
さ[a-z]*\:
せることはできないようです。
常に文字通りになることがわかっている場合はfield:
、正規表現はまったく必要ありません。
var delimiters = new String[] {"field:"};
string[] values = input.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
ただし、正規表現からfield
、コロンの前にある限り、名前は変わる可能性があると思います。単語の後に、それらの単語の次までのすべてをキャプチャすることを試みることができ:
ます(先読みを使用して)。
foreach(Match match in Regex.Matches(input, @"([a-z]+):((?:(?![a-z]+:).)*)"))
{
string fieldName = match.Groups[1].Value;
string value = match.Groups[2].Value;
}
正規表現の説明:
( # opens a capturing group; the content can later be accessed with Groups[1]
[a-z] # lower-case letter
+ # one or more of them
) # end of capturing group
: # a literal colon
( # opens a capturing group; the content can later be accessed with Groups[2]
(?: # opens a non-capturing group; just a necessary subpattern which we do not
# need later any more
(?! # negative lookahead; this will NOT match if the pattern inside matches
[a-z]+:
# a word followed by a colon; just the same as we used at the beginning of
# the regex
) # end of negative lookahead (not that this does not consume any characters;
# it LOOKS ahead)
. # any character (except for line breaks)
) # end of non-capturing group
* # 0 or more of those
) # end of capturing group
したがって、最初に一致しanylowercaseword:
ます。次に、一度にもう1つの文字を照合します。各文字について、この文字がの先頭ではないことを確認しanotherlowercaseword:
ます。キャプチャグループを使用すると、後でフィールドの名前とフィールドの値を個別に見つけることができます。
正規表現でリテラル文字列を実際に照合できることを忘れないでください。パターンが次のような場合:
field\:
「field:」は文字通り一致しますが、それ以外は一致しません。