2010-10-28 5 views
6

Disons que j'ai une chaîne multi-ligne comme ceci:Comment faire une recherche de regex "correspondance minimale" en C#?

STARTFRUIT 
banana 
ENDFRUIT 

STARTFRUIT 
avocado 
ENDFRUIT 

STARTVEGGIE 
rhubarb 
ENDVEGGIE 

STARTFRUIT 
lime 
ENDFRUIT 

Je veux chercher tous les fruits, pas de légumes. J'essaie ceci:

MatchCollection myMatches = Regex.Matches(tbBlob.Text, "STARTFRUIT.*ENDFRUIT", RegexOptions.Singleline); 

foreach (var myMatch in myMatches) 
{ 
    Forms.MessageBox.Show(String.Format("Match: {0}", myMatch), "Match", Forms.MessageBoxButtons.OK, Forms.MessageBoxIcon.Information); 
} 

Le problème est, au lieu de me retourne un tableau de trois matches, il me donne un grand match englobant la première STARTFRUIT et le début et la dernière ENDFRUIT à la fin. Existe-t-il un moyen de "minimiser" la recherche de correspondance? Je ne vois aucune aide dans RegexOptions.

Répondre

21

Utilisez un non-greedy modifier (un point d'interrogation) après la quantificateurs:

 
"STARTFRUIT.*?ENDFRUIT" 
      ^
     add this 

Notez que la marque de question a ici un sens différent ici que lorsqu'il est utilisé comme quantificateurs, où cela signifie « match nul ou un".

Questions connexes