22

文字列から名前付きグループにテキストを引き出す正規表現パターンに苦労しています。

(やや恣意的な) 例は、私が達成しようとしていることを最もよく説明しています。

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;

正規表現パターンを機能させることができないようですが、上記で十分に説明されていると思います。基本的に、人の名前、ゲームの数などを取得する必要があります。

誰でもこれを解決し、彼らが解決した実際の正規表現パターンを説明できますか?

4

4 に答える 4

28
 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>.*?)$";

他の投稿では、グループを引き出す方法について言及していますが、この正規表現は入力と一致します。

于 2012-04-26T07:13:48.383 に答える
4

のドキュメントをResult()ご覧ください。

指定された置換パターンの展開を返します。

置換パターンは必要ないため、この方法は適切なソリューションではありません。

試合のグループにアクセスしたいので、それを行います: there is a Groupsproperty .

これにより、コードは次のようになります。

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

また、russau が正しく指摘したように、あなたのパターンはテキストと一致しません:Dateは 3 文字だけではありません。

于 2012-04-26T07:08:37.683 に答える
2

これを試して:

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>...?)";

正規表現が文字列の日付部分と一致していません。

于 2012-04-26T07:08:51.223 に答える
1

正規表現が機能すると仮定すると、名前付きグループを取得するためのコードは次のようになります。

string title = match.Groups["Person"].Value;
string drawNumber = match.Groups["NumberOfGames"].Value;
于 2012-04-26T07:05:57.790 に答える