2012-04-26 13 views
19

Sono in difficoltà con un modello regex che estrarrà il testo da una stringa in gruppi denominati.Qual è il modello regex per i gruppi di acquisizione denominati in .NET?

Un esempio (alquanto arbitrario) spiegherà meglio quello che sto cercando di ottenere.

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; 

io non riesco a ottenere il modello di espressione regolare per lavorare, ma penso che la spiega sopra di esso abbastanza bene. Essenzialmente ho bisogno di ottenere il nome della persona, il numero di giochi ecc.

Qualcuno può risolvere questo e spiegare il modello regex effettivo che hanno elaborato?

risposta

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

Altri posti hanno menzionato come tirare fuori i gruppi, ma questo regex partite sul vostro input.

1

Supponendo che l'espressione regolare funziona il codice per ottenere il gruppo denominato sarebbe questo:

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

Dai un'occhiata alla the documentation for Result():

Restituisce l'espansione del criterio di sostituzione specificata.

non si desidera eventuali modelli di sostituzione, quindi questo metodo non è la soluzione giusta.

Volete accedere ai gruppi della partita, quindi fatelo: c'è a Groups property.

Con che il codice sarebbe simile a questa:

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

Inoltre, come russau giustamente osservato, il vostro modello non corrisponde il testo: Date non è solo tre caratteri.

+0

grazie, ho aggiornato la domanda con il tuo suggerimento qui, tuttavia quello che sto cercando è il modello regex. –

1

Prova questa:

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

tua espressione regolare non corrisponde la parte relativa alla data della stringa.

Problemi correlati