Partager via


Quantifieurs

Mise à jour : Juillet 2008

Les quantificateurs indiquent combien d'instances de l'élément précédent (qui peut être un caractère, un groupe ou une classe de caractères) doivent être présentes dans l'entrée pour qu'une correspondance soit trouvée.

Quantificateurs dans les expressions régulières du .NET Framework

Le tableau suivant présente les quantificateurs pris en charge par les expressions régulières du .NET Framework. Les quantités n et m sont des constantes entières. Pour en savoir plus sur la différence entre les quantificateurs gourmands et paresseux, consultez la section « Quantificateurs gourmands et paresseux » à la suite du tableau.

Quantifieur

Description

*

Correspond zéro ou plusieurs fois à l'élément qui précède. Équivalent à {0,}. * est un quantificateur gourmand dont l'équivalent non gourmand est *?.

Par exemple, l'expression régulière \b91*9*\b tente d'établir une correspondance avec le chiffre 9 après une limite de mot. 9 peut être suivi de zéro instance ou plus du chiffre 1, qui peut lui-même être suivi de zéro instance ou plus du chiffre 9. L'exemple suivant illustre cette expression régulière. La chaîne d'entrée comporte neuf chiffres dont cinq correspondent au modèle et quatre (95, 929, 9129 et 9919) n'y correspondent pas.

Dim pattern As String = "\b91*9*\b"
Dim input As String = "99 95 919 929 9119 9219 999 9919 91119"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index)
Next
' The example displays the following output:
' '99' found at position 0.
' '919' found at position 6.
' '9119' found at position 14.
' '999' found at position 24.
' '91119' found at position 33.
string pattern = "\b91*9*\b";
string input = "99 95 919 929 9119 9219 999 9919 91119";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index);
// The example displays the following output:
// '99' found at position 0.
// '919' found at position 6.
// '9119' found at position 14.
// '999' found at position 24.
// '91119' found at position 33.

+

Correspond une ou plusieurs fois à l'élément qui précède. Équivalent à {1,}. + est un quantificateur gourmand dont l'équivalent non gourmand est +?.

Par exemple, l'expression régulière \ba(n)+\w*?\b tente d'établir une correspondance avec les mots entiers qui commencent par la lettre a suivie d'une ou de plusieurs instances de la lettre n. L'exemple suivant illustre cette expression régulière. L'expression régulière établit une correspondance avec les mots an, annual, announcement et antique et pas avec les mots autumn et all.

Dim pattern As String = "\ba(n)+\w*?\b"
Dim input As String = "Autumn is a great time for an annual announcement to all antique collectors."
For Each match As Match In Regex.Matches(input, pattern, RegexOptions.IgnoreCase)
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index)
Next
' The example displays the following output:
' 'an' found at position 27.
' 'annual' found at position 30.
' 'announcement' found at position 37.
' 'antique' found at position 57.
string pattern = @"\ba(n)+\w*?\b";
string input = "Autumn is a great time for an annual announcement to all antique collectors.";
foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase))
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index);
// The example displays the following output:
// 'an' found at position 27.
// 'annual' found at position 30.
// 'announcement' found at position 37.
// 'antique' found at position 57.

?

Correspond zéro ou une fois à l'élément qui précède. Équivalent à {0,1}. ? est un quantificateur gourmand dont l'équivalent non gourmand est ??.

Par exemple, l'expression régulière \ban?\b tente d'établir une correspondance avec les mots entiers qui commencent par la lettre a suivie de zéro ou d'une instance de la lettre n. En d'autres termes, elle tente d'établir une correspondance avec les mots a et an. L'exemple suivant illustre cette expression régulière.

Dim pattern As String = "\ban?\b"
Dim input As String = "An amiable animal with a large snount and an animated nose."
For Each match As Match In Regex.Matches(input, pattern, RegexOptions.IgnoreCase)
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index)
Next
' The example displays the following output:
' 'An' found at position 0.
' 'a' found at position 23.
' 'an' found at position 42.
string pattern = @"\ban?\b";
string input = "An amiable animal with a large snount and an animated nose.";
foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase))
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index);
// The example displays the following output:
// 'An' found at position 0.
// 'a' found at position 23.
// 'an' found at position 42.

{n}

Correspond exactement n fois à l'élément qui précède. {n} est un quantificateur gourmand dont l'équivalent non gourmand est {n}?.

Par exemple, l'expression régulière \b\d+\,\d{3}\b tente d'établir une correspondance avec une limite de mot suivie d'un ou de plusieurs chiffres décimaux suivis de trois chiffres décimaux suivis d'une limite de mot. L'exemple suivant illustre cette expression régulière.

Dim pattern As String = "\b\d+\,\d{3}\b"
Dim input As String = "Sales totaled 103,524 million in January, " + _
"106,971 million in February, but only " + _
"943 million in March."
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index)
Next
' The example displays the following output:
' '103,524' found at position 14.
' '106,971' found at position 45.
string pattern = @"\b\d+\,\d{3}\b";
string input = "Sales totaled 103,524 million in January, " +
"106,971 million in February, but only " +
"943 million in March.";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index);
// The example displays the following output:
// '103,524' found at position 14.
// '106,971' found at position 45.

{n,}

Correspond au moins n fois à l'élément qui précède. {n,} est un quantificateur gourmand dont l'équivalent non gourmand est {n}?.

Par exemple, l'expression régulière \b\d{2,}\b\D+ tente d'établir une correspondance avec une limite de mot suivie d'au moins deux chiffres suivis d'une limite de mot et d'un caractère non numérique. L'exemple suivant illustre cette expression régulière. L'expression régulière ne peut pas établir de correspondance avec l'expression 7 days car elle ne contient qu'un chiffre. En revanche, une correspondance est établie avec 10 weeks et 300 years.

Dim pattern As String = "\b\d{2,}\b\D+"
Dim input As String = "7 days, 10 weeks, 300 years"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index)
Next
' The example displays the following output:
' '10 weeks, ' found at position 8.
' '300 years' found at position 18.
string pattern = @"\b\d{2,}\b\D+";
string input = "7 days, 10 weeks, 300 years";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index);
// The example displays the following output:
// '10 weeks, ' found at position 8.
// '300 years' found at position 18.

{n,m}

Correspond au moins n fois mais pas plus de m fois à l'élément qui précède. {n,m} est un quantificateur gourmand dont l'équivalent non gourmand est {n,m}?.

Par exemple, l'expression régulière (00\s){2,4} tente d'établir une correspondance avec deux à quatre occurrences de deux zéros suivis d'un espace. L'exemple suivant illustre cette expression régulière. Notez que la partie finale de la chaîne d'entrée inclut ce modèle cinq fois au lieu d'un maximum de quatre. En revanche, la partie initiale de cette sous-chaîne (jusqu'à l'espace et à la cinquième paire de zéros) correspond au modèle de l'expression régulière.

Dim pattern As String = "(00\s){2,4}"
Dim input As String = "0x00 FF 00 00 18 17 FF 00 00 00 21 00 00 00 00 00"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index)
Next
' The example displays the following output:
' '00 00 ' found at position 8.
' '00 00 00 ' found at position 23.
' '00 00 00 00 ' found at position 35.
string pattern = @"(00\s){2,4}";
string input = "0x00 FF 00 00 18 17 FF 00 00 00 21 00 00 00 00 00";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index);
// The example displays the following output:
// '00 00 ' found at position 8.
// '00 00 00 ' found at position 23.
// '00 00 00 00 ' found at position 35.

*?

Correspond zéro fois ou plus à l'élément précédent, mais le moins de fois possible. Il s'agit d'un quantificateur paresseux qui est l'équivalent du quantificateur gourmand *.

Par exemple, l'expression régulière \b\w*?oo\w*?\b établit une correspondance avec tous les mots qui contiennent la chaîne oo. L'exemple suivant illustre cette expression régulière.

Dim pattern As String = "\b\w*?oo\w*?\b"
Dim input As String = "woof root root rob oof woo woe"
For Each match As Match In Regex.Matches(input, pattern, RegexOptions.IgnoreCase)
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index)
Next
' The example displays the following output:
' 'woof' found at position 0.
' 'root' found at position 5.
' 'root' found at position 10.
' 'oof' found at position 19.
' 'woo' found at position 23.
string pattern = @"\b\w*?oo\w*?\b";
string input = "woof root root rob oof woo woe";
foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase))
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index);
// The example displays the following output:
// 'woof' found at position 0.
// 'root' found at position 5.
// 'root' found at position 10.
// 'oof' found at position 19.
// 'woo' found at position 23.

+?

Correspond une ou plusieurs fois à l'élément précédent, mais le moins de fois possible. Il s'agit d'un quantificateur paresseux qui est l'équivalent du quantificateur gourmand +.

Par exemple, l'expression régulière \b\w+?\b établit une correspondance avec un ou plusieurs caractères séparés par des limites de mot. L'exemple suivant illustre cette expression régulière.

Dim pattern As String = "\b\w+?\b"
Dim input As String = "Aa Bb Cc Dd Ee Ff"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index)
Next
' The example displays the following output:
' 'Aa' found at position 0.
' 'Bb' found at position 3.
' 'Cc' found at position 6.
' 'Dd' found at position 9.
' 'Ee' found at position 12.
' 'Ff' found at position 15.
string pattern = @"\b\w+?\b";
string input = "Aa Bb Cc Dd Ee Ff";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index);
// The example displays the following output:
// 'Aa' found at position 0.
// 'Bb' found at position 3.
// 'Cc' found at position 6.
// 'Dd' found at position 9.
// 'Ee' found at position 12.
// 'Ff' found at position 15.

??

Correspond zéro ou une fois à l'élément précédent, mais le moins de fois possible. Il s'agit d'un quantificateur paresseux qui est l'équivalent du quantificateur gourmand ?.

Par exemple, l'expression régulière ^(\s)*(System.)??Console.Write(Line)??\(?? tente d'établir une correspondance avec la chaîne Console.Write ou Console.WriteLine. La chaîne peut également inclure System. avant Console et être précédée d'une parenthèse ouvrante. Elle doit se trouver au début d'une ligne, mais peut être précédée d'un espace blanc. L'exemple suivant illustre cette expression régulière.

Dim pattern As String = "^(\s)*(System.)??Console.Write(Line)??\(??"
Dim input As String = "System.Console.WriteLine(""Hello!"")" + vbCrLf + _
"Console.Write(""Hello!"")" + vbCrLf + _
"Console.WriteLine(""Hello!"")" + vbCrLf + _
"Console.ReadLine()" + vbCrLf + _
" Console.WriteLine"
For Each match As Match In Regex.Matches(input, pattern, _
RegexOptions.IgnorePatternWhitespace Or RegexOptions.IgnoreCase Or RegexOptions.MultiLine)
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index)
Next
' The example displays the following output:
' 'System.Console.Write' found at position 0.
' 'Console.Write' found at position 36.
' 'Console.Write' found at position 61.
' ' Console.Write' found at position 110.
string pattern = @"^(\s)*(System.)??Console.Write(Line)??\(??";
string input = "System.Console.WriteLine(\"Hello!\")\n" +
"Console.Write(\"Hello!\")\n" +
"Console.WriteLine(\"Hello!\")\n" +
"Console.ReadLine()\n" +
" Console.WriteLine";
foreach (Match match in Regex.Matches(input, pattern,
RegexOptions.IgnorePatternWhitespace |
RegexOptions.IgnoreCase |
RegexOptions.Multiline))
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index);
// The example displays the following output:
// 'System.Console.Write' found at position 0.
// 'Console.Write' found at position 36.
// 'Console.Write' found at position 61.
// ' Console.Write' found at position 110.

{n}?

Correspond exactement n fois à l'élément qui précède. Il s'agit d'un quantificateur paresseux qui est l'équivalent du quantificateur gourmand {n}+.

Par exemple, l'expression régulière \b(\w{3,}?\.){2}?\w{3,}?\b correspond exactement à deux ensembles de caractères suivis d'un point sur une limite de mot. Elle est ensuite suivie d'un autre ensemble de caractères et d'une limite de mot. Cette expression régulière doit identifier l'adresse d'un site Web. L'exemple suivant illustre l'expression régulière. Notez qu'elle correspond à www.microsoft.com et mdsn.microsoft.com, mais pas à mywebsite ou mycompany.com.

Dim pattern As String = "\b(\w{3,}?\.){2}?\w{3,}?\b"
Dim input As String = "www.microsoft.com msdn.microsoft.com mywebsite mycompany.com"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index)
Next
' The example displays the following output:
' 'www.microsoft.com' found at position 0.
' 'msdn.microsoft.com' found at position 18.
string pattern = @"\b(\w{3,}?\.){2}?\w{3,}?\b";
string input = "www.microsoft.com msdn.microsoft.com mywebsite mycompany.com";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index);
// The example displays the following output:
// 'www.microsoft.com' found at position 0.
// 'msdn.microsoft.com' found at position 18.

{n,}?

Correspond au moins n fois à l'élément précédent, mais le moins de fois possible. Il s'agit d'un quantificateur paresseux qui est l'équivalent du quantificateur gourmand {n,}.

Consultez l'exemple du quantificateur {n}? pour obtenir une illustration. L'expression régulière de cet exemple utilise le quantificateur {n,} pour établir une correspondance avec au moins trois caractères suivis d'un point.

{n,m}?

Correspond entre n et m fois à l'élément précédent, mais le moins de fois possible. Il s'agit d'un quantificateur paresseux qui est l'équivalent du quantificateur gourmand {n,m}.

Par exemple, l'expression régulière \b[A-Z](\w*?\s*?){1,10}[.!?] correspond aux phrases qui contiennent entre un et dix mots. Elle établit une correspondance avec une limite de mot suivie d'une majuscule suivie de une à dix répétitions de zéro caractères alphabétiques ou plus et éventuellement d'un espace. La correspondance se termine par un point, un point d'exclamation ou un point d'interrogation. L'exemple suivant illustre cette expression régulière. Elle établit une correspondance avec toutes les phrases de la chaîne d'entrée à l'exception d'une phrase qui contient 18 mots.

Dim pattern As String = "\b[A-Z](\w*?\s*?){1,10}[.!?]"
Dim input As String = "Hi. I am writing a short note. Its purpose is " + _
"to test a regular expression that attempts to find " + _
"sentences with ten or fewer words. Most sentences " + _
"in this note are short."
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index)
Next
' The example displays the following output:
' 'Hi.' found at position 0.
' 'I am writing a short note.' found at position 4.
' 'Most sentences in this note are short.' found at position 132.
string pattern = @"\b[A-Z](\w*?\s*?){1,10}[.!?]";
string input = "Hi. I am writing a short note. Its purpose is " +
"to test a regular expression that attempts to find " +
"sentences with ten or fewer words. Most sentences " +
"in this note are short.";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index);
// The example displays the following output:
// 'Hi.' found at position 0.
// 'I am writing a short note.' found at position 4.
// 'Most sentences in this note are short.' found at position 132.

Quantifieurs gourmands et paresseux

De nombreux quantificateurs existent en deux versions :

  • Une version gourmande.

    Un quantificateur gourmand tente de correspondre autant de fois que possible à l'élément auquel il s'applique.

  • Une version non gourmande (ou paresseuse).

    Un quantificateur non gourmand tente de correspondre le moins de fois possible à l'élément auquel il s'applique.

Pour illustrer la différence, vous pouvez imaginer une expression régulière extrêmement simple destinée à extraire les quatre derniers chiffres d'une chaîne de nombres telle qu'un numéro de carte de crédit. La version de l'expression régulière qui utilise le quantificateur gourmand * est \b.*([0-9]{4})\b. Cependant, dans le cas d'une chaîne qui contient deux nombres, elle ne peut afficher que les quatre derniers chiffres du deuxième nombre, comme le montre l'exemple suivant.

Dim greedyPattern As String = "\b.*([0-9]{4})\b"
Dim input1 As String = "1112223333 3992991999"
For Each match As Match In Regex.Matches(input1, greedypattern)
   Console.WriteLine("Account ending in ******{0}.", match.Groups(1).Value)
Next
' The example displays the following output:
'       Account ending in ******1999.
string greedyPattern = @"\b.*([0-9]{4})\b";
string input1 = "1112223333 3992991999";
foreach (Match match in Regex.Matches(input1, greedyPattern))
   Console.WriteLine("Account ending in ******{0}.", match.Groups[1].Value);

// The example displays the following output:
//       Account ending in ******1999.

Il ne s'agit pas du comportement souhaité. L'expression régulière ne parvient pas à afficher le premier nombre car le quantificateur * tente d'établir une correspondance autant de fois que possible avec l'élément qui précède et atteint ainsi la fin de la chaîne.

Une expression régulière équivalente qui utilise le quantificateur paresseux *? aboutit au comportement attendu, comme le montre l'exemple suivant.

Dim lazyPattern As String = "\b.*?([0-9]{4})\b"
Dim input2 As String = "1112223333 3992991999"
For Each match As Match In Regex.Matches(input2, lazypattern)
   Console.WriteLine("Account ending in ******{0}.", match.Groups(1).Value)
Next     
' The example displays the following output:
'       Account ending in ******3333.
'       Account ending in ******1999.
string lazyPattern = @"\b.*?([0-9]{4})\b";
string input2 = "1112223333 3992991999";
foreach (Match match in Regex.Matches(input2, lazyPattern))
   Console.WriteLine("Account ending in ******{0}.", match.Groups[1].Value);

// The example displays the following output:
//       Account ending in ******3333.
//       Account ending in ******1999.

Dans la plupart des cas, les expressions régulières avec des quantificateurs gourmands et paresseux retournent les mêmes correspondances. Elles retournent le plus souvent des résultats différents lorsqu'elles sont utilisées avec le métacaractère « point » (. ), qui correspond à n'importe quel caractère.

Voir aussi

Autres ressources

Éléments du langage des expressions régulières

Historique des modifications

Date

Historique

Raison

Juillet 2008

Nombreuses modifications.

Résolution des bogues de contenu.