2012-04-26 47 views
19

文字列から名前付きグループにテキストを引き出す正規表現パターンに苦労しています。.NETで名前付きキャプチャグループの正規表現パターンとは何ですか?

私は何を達成しようとしているのかをよく説明します。

string input = 
    "Mary Anne has been to 949 bingo games. The last was on Tue 24/04/2012. She won with the Numbers: 4, 6, 11, 16, 19, 27, 45"; 

string pattern = 
    @"(?<Person>\w+?) has been to (?<NumberOfGames>\d+?) bingo games. The last was on (?<Day>...?) (?<Date>...?). She won with the Numbers: (?<Numbers>...?)"; 

Regex regex = new Regex(pattern); 
var match = regex.Match(input); 

string person = match.Groups["Person"].Value; 
string noOfGames = match.Groups["NumberOfGames"].Value; 
string day = match.Groups["Day"].Value; 
string date = match.Groups["Date"].Value; 
string numbers = match.Groups["Numbers"].Value; 

私が動作するように正規表現パターンを得るように見えることはできませんが、私は上記の、それは十分に説明してだと思います。基本的に私は、人の名前、ゲームの数などを取得する必要があります

誰もこれを解決し、実際の正規表現のパターンを説明することができますか?正規表現は、名前のグループを取得するためのコードを動作すると仮定すると、

答えて

25
string pattern = @"(?<Person>[\w ]+) has been to (?<NumberOfGames>\d+) bingo games\. The last was on (?<Day>\w+) (?<Date>\d\d/\d\d/\d{4})\. She won with the Numbers: (?<Numbers>.*?)$"; 

他の投稿ではグループの引き出し方法が記載されていますが、この正規表現は入力内容と一致します。

1

はこのようになります:

string title = match.Groups["Person"].Value; 
string drawNumber = match.Groups["NumberOfGames"].Value; 
5

the documentation for Result()を見てください:

指定された置換パターンの拡大を返し

代替パターンは必要ありません。この方法は正しい解決策ではありません。

あなたは試合のグループにアクセスしたいので、それを実行してください:a Groups propertyです。あなたのコードは次のようになりますことをして

string title = match.Groups["Person"].Value; 
string drawNumber = match.Groups["NumberOfGames"].Value; 

また、russauが正しく指摘したように、あなたのパターンは、あなたのテキストと一致しません:Dateはわずか3文字ではありません。あなたの正規表現は、文字列の日付部分に一致していない

string pattern = @"(?<Person>\w+?) has been to (?<NumberOfGames>\d+?) bingo games. The last was on (?<Day>...?) (?<Date>\d+/\d+/\d+). She won with the Numbers: (?<Numbers>...?)"; 

+0

ありがとう、私はここであなたの提案で質問を更新しましたが、私は後に正規表現のパターンです。 –

1

はこれを試してみてください。

関連する問題