Regex.Matches Méthode
Définition
Recherche dans une chaîne d'entrée toutes les occurrences d'une expression régulière et retourne toutes les correspondances.Searches an input string for all occurrences of a regular expression and returns all the matches.
Surcharges
Matches(String) |
Recherche dans la chaîne d'entrée spécifiée toutes les occurrences d'une expression régulière.Searches the specified input string for all occurrences of a regular expression. |
Matches(String, Int32) |
Recherche dans la chaîne d'entrée spécifiée toutes les occurrences d'une expression régulière, en commençant à la position de démarrage spécifiée dans la chaîne.Searches the specified input string for all occurrences of a regular expression, beginning at the specified starting position in the string. |
Matches(String, String) |
Recherche dans la chaîne d'entrée spécifiée toutes les occurrences d'une expression régulière spécifiée.Searches the specified input string for all occurrences of a specified regular expression. |
Matches(String, String, RegexOptions) |
Recherche dans la chaîne d'entrée spécifiée toutes les occurrences d'une expression régulière spécifique, en utilisant les options de correspondance spécifiées.Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options. |
Matches(String, String, RegexOptions, TimeSpan) |
Recherche dans la chaîne d'entrée spécifiée toutes les occurrences d'une expression régulière spécifiée, en utilisant les options de correspondance et l'intervalle de délai d'attente spécifiés.Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options and time-out interval. |
Matches(String)
Recherche dans la chaîne d'entrée spécifiée toutes les occurrences d'une expression régulière.Searches the specified input string for all occurrences of a regular expression.
public:
System::Text::RegularExpressions::MatchCollection ^ Matches(System::String ^ input);
public System.Text.RegularExpressions.MatchCollection Matches (string input);
member this.Matches : string -> System.Text.RegularExpressions.MatchCollection
Public Function Matches (input As String) As MatchCollection
Paramètres
- input
- String
Chaîne dans laquelle une correspondance doit être recherchée.The string to search for a match.
Retours
Collection des objets Match trouvés par la recherche.A collection of the Match objects found by the search. Si aucune correspondance n'est trouvée, la méthode retourne un objet de collection vide.If no matches are found, the method returns an empty collection object.
Exceptions
input
est null
.input
is null
.
Exemples
L’exemple suivant utilise la Matches(String) méthode pour identifier tous les mots d’une phrase qui se terminent par «es».The following example uses the Matches(String) method to identify any words in a sentence that end in "es".
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b\w+es\b";
Regex rgx = new Regex(pattern);
string sentence = "Who writes these notes?";
foreach (Match match in rgx.Matches(sentence))
Console.WriteLine("Found '{0}' at position {1}",
match.Value, match.Index);
}
}
// The example displays the following output:
// Found 'writes' at position 4
// Found 'notes' at position 17
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b\w+es\b"
Dim rgx As New Regex(pattern)
Dim sentence As String = "Who writes these notes?"
For Each match As Match In rgx.Matches(sentence)
Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index)
Next
End Sub
End Module
' The example displays the following output:
' Found 'writes' at position 4
' Found 'notes' at position 17
Le modèle d'expression régulière \b\w+es\b
est défini comme indiqué dans le tableau suivant.The regular expression pattern \b\w+es\b
is defined as shown in the following table.
MotifPattern | DescriptionDescription |
---|---|
\b |
Commencer la correspondance à la limite d'un mot.Begin the match at a word boundary. |
\w+ |
Mettre en correspondance un ou plusieurs caractères alphabétiques.Match one or more word characters. |
es |
Correspond à la chaîne littérale «es».Match the literal string "es". |
\b |
Terminer la correspondance à la limite d'un mot.End the match at a word boundary. |
Remarques
La Matches(String) méthode est semblable à la Match(String) méthode, sauf qu’elle retourne des informations sur toutes les correspondances trouvées dans la chaîne d’entrée, au lieu d’une correspondance unique.The Matches(String) method is similar to the Match(String) method, except that it returns information about all the matches found in the input string, instead of a single match. Elle est équivalente au code suivant:It is equivalent to the following code:
Match match = regex.Match(input);
while (match.Success) {
// Handle match here...
match = match.NextMatch();
}
Dim match As Match = regex.Match(input)
Do While match.Success
' Handle match here...
match = match.NextMatch()
Loop
La collection comprend uniquement les correspondances et se termine à la première non-correspondance.The collection includes only matches and terminates at the first non-match.
Le modèle d’expression régulière pour lequel Matches(String) la méthode effectue la recherche est défini par l’appel à Regex l’un des constructeurs de classe.The regular expression pattern for which the Matches(String) method searches is defined by the call to one of the Regex class constructors. Pour plus d’informations sur les éléments qui peuvent former un modèle d’expression régulière, consultez langage des expressions régulières-aide-mémoire.For more information about the elements that can form a regular expression pattern, see Regular Expression Language - Quick Reference.
La Matches méthode utilise l’évaluation paresseuse pour remplir l' MatchCollection objet retourné.The Matches method uses lazy evaluation to populate the returned MatchCollection object. L’accès aux membres de cette collection, MatchCollection.Count tels MatchCollection.CopyTo que et, entraîne le remplissage immédiat de la collection.Accessing members of this collection such as MatchCollection.Count and MatchCollection.CopyTo causes the collection to be populated immediately. Pour tirer parti de l’évaluation différée, vous devez effectuer une itération de la collection à foreach
l' C# aide For Each
d’une construction telle que dans et...Next
To take advantage of lazy evaluation, you should iterate the collection by using a construct such as foreach
in C# and For Each
…Next
en Visual Basic.in Visual Basic.
En raison de son évaluation différée, Matches(String) l’appel de la méthode RegexMatchTimeoutException ne lève pas d’exception.Because of its lazy evaluation, calling the Matches(String) method does not throw a RegexMatchTimeoutException exception. Toutefois, l’exception est levée lorsqu’une opération est exécutée sur MatchCollection l’objet retourné par cette méthode, si MatchTimeout la propriété n' Regex.InfiniteMatchTimeout est pas et qu’une opération de correspondance dépasse l’intervalle de délai d’attente.However, the exception is thrown when an operation is performed on the MatchCollection object returned by this method, if the MatchTimeout property is not Regex.InfiniteMatchTimeout and a matching operation exceeds the time-out interval.
Voir aussi
Matches(String, Int32)
Recherche dans la chaîne d'entrée spécifiée toutes les occurrences d'une expression régulière, en commençant à la position de démarrage spécifiée dans la chaîne.Searches the specified input string for all occurrences of a regular expression, beginning at the specified starting position in the string.
public:
System::Text::RegularExpressions::MatchCollection ^ Matches(System::String ^ input, int startat);
public System.Text.RegularExpressions.MatchCollection Matches (string input, int startat);
member this.Matches : string * int -> System.Text.RegularExpressions.MatchCollection
Public Function Matches (input As String, startat As Integer) As MatchCollection
Paramètres
- input
- String
Chaîne dans laquelle une correspondance doit être recherchée.The string to search for a match.
- startat
- Int32
Position du caractère dans la chaîne d'entrée à partir duquel commencer la recherche.The character position in the input string at which to start the search.
Retours
Collection des objets Match trouvés par la recherche.A collection of the Match objects found by the search. Si aucune correspondance n'est trouvée, la méthode retourne un objet de collection vide.If no matches are found, the method returns an empty collection object.
Exceptions
input
a la valeur null
.input
is null
.
startat
est inférieur à zéro ou supérieur à la longueur de input
.startat
is less than zero or greater than the length of input
.
Exemples
L’exemple suivant utilise la Match(String) méthode pour rechercher le premier mot d’une phrase qui se termine par «es», puis appelle Matches(String, Int32) la méthode pour identifier tous les mots supplémentaires qui se terminent par «es».The following example uses the Match(String) method to find the first word in a sentence that ends in "es", and then calls the Matches(String, Int32) method to identify any additional words that end in "es".
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b\w+es\b";
Regex rgx = new Regex(pattern);
string sentence = "Who writes these notes and uses our paper?";
// Get the first match.
Match match = rgx.Match(sentence);
if (match.Success) {
Console.WriteLine("Found first 'es' in '{0}' at position {1}",
match.Value, match.Index);
// Get any additional matches.
foreach (Match m in rgx.Matches(sentence, match.Index + match.Length))
Console.WriteLine("Also found '{0}' at position {1}",
m.Value, m.Index);
}
}
}
// The example displays the following output:
// Found first 'es' in 'writes' at position 4
// Also found 'notes' at position 17
// Also found 'uses' at position 27
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b\w+es\b"
Dim rgx As New Regex(pattern)
Dim sentence As String = "Who writes these notes and uses our paper?"
' Get the first match.
Dim match As Match = rgx.Match(sentence)
If match.Success Then
Console.WriteLine("Found first 'es' in '{0}' at position {1}", _
match.Value, match.Index)
' Get any additional matches.
For Each match In rgx.Matches(sentence, match.Index + match.Length)
Console.WriteLine("Also found '{0}' at position {1}", _
match.Value, match.Index)
Next
End If
End Sub
End Module
' The example displays the following output:
' Found first 'es' in 'writes' at position 4
' Also found 'notes' at position 17
' Also found 'uses' at position 27
Le modèle d'expression régulière \b\w+es\b
est défini comme indiqué dans le tableau suivant.The regular expression pattern \b\w+es\b
is defined as shown in the following table.
MotifPattern | DescriptionDescription |
---|---|
\b |
Commencer la correspondance à la limite d'un mot.Begin the match at a word boundary. |
\w+ |
Mettre en correspondance un ou plusieurs caractères alphabétiques.Match one or more word characters. |
es |
Correspond à la chaîne littérale «es».Match the literal string "es". |
\b |
Terminer la correspondance à la limite d'un mot.End the match at a word boundary. |
Remarques
La Matches(String, Int32) méthode est semblable à la Match(String, Int32) méthode, sauf qu’elle retourne des informations sur toutes les correspondances trouvées dans la chaîne d’entrée, au lieu d’une correspondance unique.The Matches(String, Int32) method is similar to the Match(String, Int32) method, except that it returns information about all the matches found in the input string, instead of a single match. Elle est équivalente au code suivant:It is equivalent to the following code:
Match match = regex.Match(input, startAt);
while (match.Success) {
// Handle match here...
match = match.NextMatch();
}
Dim match As Match = regex.Match(input, startAt)
Do While match.Success
' Handle match here...
match = match.NextMatch()
Loop
Le modèle d’expression régulière pour lequel Matches(String, Int32) la méthode effectue la recherche est défini par l’appel à Regex l’un des constructeurs de classe.The regular expression pattern for which the Matches(String, Int32) method searches is defined by the call to one of the Regex class constructors. Pour plus d’informations sur les éléments qui peuvent former un modèle d’expression régulière, consultez langage des expressions régulières-aide-mémoire.For more information about the elements that can form a regular expression pattern, see Regular Expression Language - Quick Reference.
La Matches méthode utilise l’évaluation paresseuse pour remplir l' MatchCollection objet retourné.The Matches method uses lazy evaluation to populate the returned MatchCollection object. L’accès aux membres de cette collection, MatchCollection.Count tels MatchCollection.CopyTo que et, entraîne le remplissage immédiat de la collection.Accessing members of this collection such as MatchCollection.Count and MatchCollection.CopyTo causes the collection to be populated immediately. Pour tirer parti de l’évaluation différée, vous devez effectuer une itération de la collection à foreach
l' C# aide For Each
d’une construction telle que dans et...Next
To take advantage of lazy evaluation, you should iterate the collection by using a construct such as foreach
in C# and For Each
…Next
en Visual Basic.in Visual Basic.
En raison de son évaluation différée, Matches(String, Int32) l’appel de la méthode RegexMatchTimeoutException ne lève pas d’exception.Because of its lazy evaluation, calling the Matches(String, Int32) method does not throw a RegexMatchTimeoutException exception. Toutefois, l’exception est levée lorsqu’une opération est exécutée sur MatchCollection l’objet retourné par cette méthode, si MatchTimeout la propriété n' Regex.InfiniteMatchTimeout est pas et qu’une opération de correspondance dépasse l’intervalle de délai d’attente.However, the exception is thrown when an operation is performed on the MatchCollection object returned by this method, if the MatchTimeout property is not Regex.InfiniteMatchTimeout and a matching operation exceeds the time-out interval.
Voir aussi
Matches(String, String)
Recherche dans la chaîne d'entrée spécifiée toutes les occurrences d'une expression régulière spécifiée.Searches the specified input string for all occurrences of a specified regular expression.
public:
static System::Text::RegularExpressions::MatchCollection ^ Matches(System::String ^ input, System::String ^ pattern);
public static System.Text.RegularExpressions.MatchCollection Matches (string input, string pattern);
static member Matches : string * string -> System.Text.RegularExpressions.MatchCollection
Public Shared Function Matches (input As String, pattern As String) As MatchCollection
Paramètres
- input
- String
Chaîne dans laquelle une correspondance doit être recherchée.The string to search for a match.
- pattern
- String
Modèle d’expression régulière à mettre en correspondance.The regular expression pattern to match.
Retours
Collection des objets Match trouvés par la recherche.A collection of the Match objects found by the search. Si aucune correspondance n'est trouvée, la méthode retourne un objet de collection vide.If no matches are found, the method returns an empty collection object.
Exceptions
Une erreur d’analyse d’expression régulière s’est produite.A regular expression parsing error occurred.
input
ou pattern
est null
.input
or pattern
is null
.
Exemples
L’exemple suivant utilise la Matches(String, String) méthode pour identifier les mots d’une phrase qui se terminent par «es».The following example uses the Matches(String, String) method to identify any word in a sentence that ends in "es".
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b\w+es\b";
string sentence = "Who writes these notes?";
foreach (Match match in Regex.Matches(sentence, pattern))
Console.WriteLine("Found '{0}' at position {1}",
match.Value, match.Index);
}
}
// The example displays the following output:
// Found 'writes' at position 4
// Found 'notes' at position 17
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b\w+es\b"
Dim sentence As String = "Who writes these notes?"
For Each match As Match In Regex.Matches(sentence, pattern)
Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index)
Next
End Sub
End Module
' The example displays the following output:
' Found 'writes' at position 4
' Found 'notes' at position 17
Le modèle d'expression régulière \b\w+es\b
est défini comme indiqué dans le tableau suivant.The regular expression pattern \b\w+es\b
is defined as shown in the following table.
MotifPattern | DescriptionDescription |
---|---|
\b |
Commencer la correspondance à la limite d'un mot.Begin the match at a word boundary. |
\w+ |
Mettre en correspondance un ou plusieurs caractères alphabétiques.Match one or more word characters. |
es |
Correspond à la chaîne littérale «es».Match the literal string "es". |
\b |
Terminer la correspondance à la limite d'un mot.End the match at a word boundary. |
Remarques
La Matches(String, String) méthode est semblable à la Match(String, String) méthode, sauf qu’elle retourne des informations sur toutes les correspondances trouvées dans la chaîne d’entrée, au lieu d’une correspondance unique.The Matches(String, String) method is similar to the Match(String, String) method, except that it returns information about all the matches found in the input string, instead of a single match. Elle est équivalente au code suivant:It is equivalent to the following code:
Match match = Regex.Match(input, pattern);
while (match.Success) {
// Handle match here...
match = match.NextMatch();
}
Dim match As Match = Regex.Match(input, pattern)
Do While match.Success
' Handle match here...
match = match.NextMatch()
Loop
Les méthodes Matches
statiques sont équivalentes à la Regex construction d’un objet avec le modèle d’expression régulière spécifié et Matches
à l’appel de la méthode d’instance.The static Matches
methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Matches
.
Le pattern
paramètre se compose d’éléments de langage d’expression régulière qui décrivent symboliquement la chaîne à faire correspondre.The pattern
parameter consists of regular expression language elements that symbolically describe the string to match. Pour plus d’informations sur les expressions régulières, consultez .NET Framework des expressions régulières et le langage des expressions régulières-aide-mémoire.For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.
La Matches méthode utilise l’évaluation paresseuse pour remplir l' MatchCollection objet retourné.The Matches method uses lazy evaluation to populate the returned MatchCollection object. L’accès aux membres de cette collection, MatchCollection.Count tels MatchCollection.CopyTo que et, entraîne le remplissage immédiat de la collection.Accessing members of this collection such as MatchCollection.Count and MatchCollection.CopyTo causes the collection to be populated immediately. Pour tirer parti de l’évaluation différée, vous devez effectuer une itération de la collection à foreach
l' C# aide For Each
d’une construction telle que dans et...Next
To take advantage of lazy evaluation, you should iterate the collection by using a construct such as foreach
in C# and For Each
…Next
en Visual Basic.in Visual Basic.
En raison de son évaluation différée, Matches(String, String) l’appel de la méthode RegexMatchTimeoutException ne lève pas d’exception.Because of its lazy evaluation, calling the Matches(String, String) method does not throw a RegexMatchTimeoutException exception. Toutefois, l’exception est levée lorsqu’une opération est exécutée sur MatchCollection l’objet retourné par cette méthode, si un intervalle de délai d’attente est défini par la propriété «REGEX_DEFAULT_MATCH_TIMEOUT» du domaine d’application actuel et une opération de correspondance dépasse cet intervalle de délai d’attente.However, the exception is thrown when an operation is performed on the MatchCollection object returned by this method, if a time-out interval is defined by the "REGEX_DEFAULT_MATCH_TIMEOUT" property of the current application domain and a matching operation exceeds this time-out interval.
Notes pour les appelants
Cette méthode expire après un intervalle qui est égal à la valeur du délai d’attente par défaut du domaine d’application dans lequel elle est appelée.This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. Si aucune valeur de délai d’attente n’a été définie pour le domaine d’application, InfiniteMatchTimeoutla valeur, qui empêche l’expiration du délai d’attente de la méthode, est utilisée.If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. La méthode statique recommandée pour la récupération de plusieurs correspondances Matches(String, String, RegexOptions, TimeSpan)de modèle est, ce qui vous permet de spécifier l’intervalle de délai d’attente.The recommended static method for retrieving multiple pattern matches is Matches(String, String, RegexOptions, TimeSpan), which lets you specify the time-out interval.
Voir aussi
Matches(String, String, RegexOptions)
Recherche dans la chaîne d'entrée spécifiée toutes les occurrences d'une expression régulière spécifique, en utilisant les options de correspondance spécifiées.Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options.
public:
static System::Text::RegularExpressions::MatchCollection ^ Matches(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options);
public static System.Text.RegularExpressions.MatchCollection Matches (string input, string pattern, System.Text.RegularExpressions.RegexOptions options);
static member Matches : string * string * System.Text.RegularExpressions.RegexOptions -> System.Text.RegularExpressions.MatchCollection
Public Shared Function Matches (input As String, pattern As String, options As RegexOptions) As MatchCollection
Paramètres
- input
- String
Chaîne dans laquelle une correspondance doit être recherchée.The string to search for a match.
- pattern
- String
Modèle d’expression régulière à mettre en correspondance.The regular expression pattern to match.
- options
- RegexOptions
Combinaison de bits de valeurs d'énumération qui spécifient des options pour la correspondance.A bitwise combination of the enumeration values that specify options for matching.
Retours
Collection des objets Match trouvés par la recherche.A collection of the Match objects found by the search. Si aucune correspondance n'est trouvée, la méthode retourne un objet de collection vide.If no matches are found, the method returns an empty collection object.
Exceptions
Une erreur d’analyse d’expression régulière s’est produite.A regular expression parsing error occurred.
input
ou pattern
a la valeur null
.input
or pattern
is null
.
options
n’est pas une combinaison d’opérations au niveau du bit de valeurs RegexOptions.options
is not a valid bitwise combination of RegexOptions values.
Exemples
L’exemple suivant appelle la Matches(String, String) méthode pour identifier tout mot dans une phrase qui se termine par «es», puis appelle Matches(String, String, RegexOptions) la méthode pour effectuer une comparaison qui ne respecte pas la casse du modèle avec la chaîne d’entrée.The following example calls the Matches(String, String) method to identify any word in a sentence that ends in "es", and then calls the Matches(String, String, RegexOptions) method to perform a case-insensitive comparison of the pattern with the input string. Comme le montre la sortie, les deux méthodes retournent des résultats différents.As the output shows, the two methods return different results.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b\w+es\b";
string sentence = "NOTES: Any notes or comments are optional.";
// Call Matches method without specifying any options.
foreach (Match match in Regex.Matches(sentence, pattern))
Console.WriteLine("Found '{0}' at position {1}",
match.Value, match.Index);
Console.WriteLine();
// Call Matches method for case-insensitive matching.
foreach (Match match in Regex.Matches(sentence, pattern, RegexOptions.IgnoreCase))
Console.WriteLine("Found '{0}' at position {1}",
match.Value, match.Index);
}
}
// The example displays the following output:
// Found 'notes' at position 11
//
// Found 'NOTES' at position 0
// Found 'notes' at position 11
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b\w+es\b"
Dim sentence As String = "NOTES: Any notes or comments are optional."
' Call Matches method without specifying any options.
For Each match As Match In Regex.Matches(sentence, pattern)
Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index)
Next
Console.WriteLine()
' Call Matches method for case-insensitive matching.
For Each match As Match In Regex.Matches(sentence, pattern, RegexOptions.IgnoreCase)
Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index)
Next
End Sub
End Module
' The example displays the following output:
' Found 'notes' at position 11
'
' Found 'NOTES' at position 0
' Found 'notes' at position 11
Le modèle d'expression régulière \b\w+es\b
est défini comme indiqué dans le tableau suivant.The regular expression pattern \b\w+es\b
is defined as shown in the following table.
MotifPattern | DescriptionDescription |
---|---|
\b |
Commencer la correspondance à la limite d'un mot.Begin the match at a word boundary. |
\w+ |
Mettre en correspondance un ou plusieurs caractères alphabétiques.Match one or more word characters. |
es |
Correspond à la chaîne littérale «es».Match the literal string "es". |
\b |
Terminer la correspondance à la limite d'un mot.End the match at a word boundary. |
Remarques
La Matches(String, String, RegexOptions) méthode est semblable à la Match(String, String, RegexOptions) méthode, sauf qu’elle retourne des informations sur toutes les correspondances trouvées dans la chaîne d’entrée, au lieu d’une correspondance unique.The Matches(String, String, RegexOptions) method is similar to the Match(String, String, RegexOptions) method, except that it returns information about all the matches found in the input string, instead of a single match. Elle est équivalente au code suivant:It is equivalent to the following code:
Match match = Regex.Match(input, pattern, options);
while (match.Success) {
// Handle match here...
match = match.NextMatch();
}
Dim match As Match = Regex.Match(input, pattern, options)
Do While match.Success
' Handle match here...
match = match.NextMatch()
Loop
Les méthodes Matches
statiques sont équivalentes à la Regex construction d’un objet avec le modèle d’expression régulière spécifié et Matches
à l’appel de la méthode d’instance.The static Matches
methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Matches
.
Le pattern
paramètre se compose d’éléments de langage d’expression régulière qui décrivent symboliquement la chaîne à faire correspondre.The pattern
parameter consists of regular expression language elements that symbolically describe the string to match. Pour plus d’informations sur les expressions régulières, consultez .NET Framework des expressions régulières et le langage des expressions régulières-aide-mémoire.For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.
La Matches méthode utilise l’évaluation paresseuse pour remplir l' MatchCollection objet retourné.The Matches method uses lazy evaluation to populate the returned MatchCollection object. L’accès aux membres de cette collection, MatchCollection.Count tels MatchCollection.CopyTo que et, entraîne le remplissage immédiat de la collection.Accessing members of this collection such as MatchCollection.Count and MatchCollection.CopyTo causes the collection to be populated immediately. Pour tirer parti de l’évaluation différée, vous devez effectuer une itération de la collection à foreach
l' C# aide For Each
d’une construction telle que dans et...Next
To take advantage of lazy evaluation, you should iterate the collection by using a construct such as foreach
in C# and For Each
…Next
en Visual Basic.in Visual Basic.
En raison de son évaluation différée, Matches(String, String) l’appel de la méthode RegexMatchTimeoutException ne lève pas d’exception.Because of its lazy evaluation, calling the Matches(String, String) method does not throw a RegexMatchTimeoutException exception. Toutefois, l’exception est levée lorsqu’une opération est exécutée sur MatchCollection l’objet retourné par cette méthode, si un intervalle de délai d’attente est défini par la propriété «REGEX_DEFAULT_MATCH_TIMEOUT» du domaine d’application actuel et une opération de correspondance dépasse cet intervalle de délai d’attente.However, the exception is thrown when an operation is performed on the MatchCollection object returned by this method, if a time-out interval is defined by the "REGEX_DEFAULT_MATCH_TIMEOUT" property of the current application domain and a matching operation exceeds this time-out interval.
Notes pour les appelants
Cette méthode expire après un intervalle qui est égal à la valeur du délai d’attente par défaut du domaine d’application dans lequel elle est appelée.This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. Si aucune valeur de délai d’attente n’a été définie pour le domaine d’application, InfiniteMatchTimeoutla valeur, qui empêche l’expiration du délai d’attente de la méthode, est utilisée.If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. La méthode statique recommandée pour la récupération de plusieurs correspondances Matches(String, String, RegexOptions, TimeSpan)de modèle est, ce qui vous permet de définir l’intervalle de délai d’attente.The recommended static method for retrieving multiple pattern matches is Matches(String, String, RegexOptions, TimeSpan), which lets you set the time-out interval.
Voir aussi
Matches(String, String, RegexOptions, TimeSpan)
Recherche dans la chaîne d'entrée spécifiée toutes les occurrences d'une expression régulière spécifiée, en utilisant les options de correspondance et l'intervalle de délai d'attente spécifiés.Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options and time-out interval.
public:
static System::Text::RegularExpressions::MatchCollection ^ Matches(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public static System.Text.RegularExpressions.MatchCollection Matches (string input, string pattern, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
static member Matches : string * string * System.Text.RegularExpressions.RegexOptions * TimeSpan -> System.Text.RegularExpressions.MatchCollection
Public Shared Function Matches (input As String, pattern As String, options As RegexOptions, matchTimeout As TimeSpan) As MatchCollection
Paramètres
- input
- String
Chaîne dans laquelle une correspondance doit être recherchée.The string to search for a match.
- pattern
- String
Modèle d’expression régulière à mettre en correspondance.The regular expression pattern to match.
- options
- RegexOptions
Combinaison de bits de valeurs d'énumération qui spécifient des options pour la correspondance.A bitwise combination of the enumeration values that specify options for matching.
- matchTimeout
- TimeSpan
Intervalle de délai d’attente ou InfiniteMatchTimeout pour indiquer que la méthode ne doit pas expirer.A time-out interval, or InfiniteMatchTimeout to indicate that the method should not time out.
Retours
Collection des objets Match trouvés par la recherche.A collection of the Match objects found by the search. Si aucune correspondance n'est trouvée, la méthode retourne un objet de collection vide.If no matches are found, the method returns an empty collection object.
Exceptions
Une erreur d’analyse d’expression régulière s’est produite.A regular expression parsing error occurred.
input
ou pattern
est null
.input
or pattern
is null
.
options
n’est pas une combinaison d’opérations au niveau du bit de valeurs RegexOptions .options
is not a valid bitwise combination of RegexOptions values.
- ou --or-
matchTimeout
a une valeur négative, nulle ou supérieure à environ 24 jours.matchTimeout
is negative, zero, or greater than approximately 24 days.
Exemples
L’exemple suivant appelle la Matches(String, String, RegexOptions, TimeSpan) méthode pour effectuer une comparaison respectant la casse qui correspond à n’importe quel mot dans une phrase qui se termine par «es».The following example calls the Matches(String, String, RegexOptions, TimeSpan) method to perform a case-sensitive comparison that matches any word in a sentence that ends in "es". Il appelle ensuite la Matches(String, String, RegexOptions, TimeSpan) méthode pour effectuer une comparaison qui ne respecte pas la casse du modèle avec la chaîne d’entrée.It then calls the Matches(String, String, RegexOptions, TimeSpan) method to perform a case-insensitive comparison of the pattern with the input string. Dans les deux cas, l’intervalle de délai d’attente est défini à une seconde.In both cases, the time-out interval is set to one second. Comme le montre la sortie, les deux méthodes retournent des résultats différents.As the output shows, the two methods return different results.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b\w+es\b";
string sentence = "NOTES: Any notes or comments are optional.";
// Call Matches method without specifying any options.
try {
foreach (Match match in Regex.Matches(sentence, pattern,
RegexOptions.None,
TimeSpan.FromSeconds(1)))
Console.WriteLine("Found '{0}' at position {1}",
match.Value, match.Index);
}
catch (RegexMatchTimeoutException) {
// Do Nothing: Assume that timeout represents no match.
}
Console.WriteLine();
// Call Matches method for case-insensitive matching.
try {
foreach (Match match in Regex.Matches(sentence, pattern, RegexOptions.IgnoreCase))
Console.WriteLine("Found '{0}' at position {1}",
match.Value, match.Index);
}
catch (RegexMatchTimeoutException) {}
}
}
// The example displays the following output:
// Found 'notes' at position 11
//
// Found 'NOTES' at position 0
// Found 'notes' at position 11
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b\w+es\b"
Dim sentence As String = "NOTES: Any notes or comments are optional."
' Call Matches method without specifying any options.
For Each match As Match In Regex.Matches(sentence, pattern,
RegexOptions.None,
TimeSpan.FromSeconds(1))
Try
Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index)
Catch e As RegexMatchTimeoutException
' Do Nothing: Assume that timeout represents no match.
End Try
Next
Console.WriteLine()
' Call Matches method for case-insensitive matching.
Try
For Each match As Match In Regex.Matches(sentence, pattern,
RegexOptions.IgnoreCase,
TimeSpan.FromSeconds(1))
Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index)
Next
Catch de As RegexMatchTimeoutException
' Do Nothing: Assume that timeout represents no match.
End Try
End Sub
End Module
' The example displays the following output:
' Found 'notes' at position 11
'
' Found 'NOTES' at position 0
' Found 'notes' at position 11
Le modèle d'expression régulière \b\w+es\b
est défini comme indiqué dans le tableau suivant.The regular expression pattern \b\w+es\b
is defined as shown in the following table.
MotifPattern | DescriptionDescription |
---|---|
\b |
Commencer la correspondance à la limite d'un mot.Begin the match at a word boundary. |
\w+ |
Mettre en correspondance un ou plusieurs caractères alphabétiques.Match one or more word characters. |
es |
Correspond à la chaîne littérale «es».Match the literal string "es". |
\b |
Terminer la correspondance à la limite d'un mot.End the match at a word boundary. |
Remarques
La Matches(String, String, RegexOptions, TimeSpan) méthode est semblable à la Match(String, String, RegexOptions, TimeSpan) méthode, sauf qu’elle retourne des informations sur toutes les correspondances trouvées dans la chaîne d’entrée, au lieu d’une correspondance unique.The Matches(String, String, RegexOptions, TimeSpan) method is similar to the Match(String, String, RegexOptions, TimeSpan) method, except that it returns information about all the matches found in the input string, instead of a single match. Elle est équivalente au code suivant:It is equivalent to the following code:
try {
Match match = Regex.Match(input, pattern, options,
TimeSpan.FromSeconds(1));
while (match.Success) {
// Handle match here...
match = match.NextMatch();
}
}
catch (RegexMatchTimeoutException) {
// Do nothing: assume that exception represents no match.
}
Try
Dim match As Match = Regex.Match(input, pattern, options,
TimeSpan.FromSeconds(1))
Do While match.Success
' Handle match here...
match = match.NextMatch()
Loop
Catch e As RegexMatchTimeoutException
' Do nothing: assume that exception represents no match.
End Try
Les méthodes Matches
statiques sont équivalentes à la Regex construction d’un objet avec le modèle d’expression régulière spécifié et Matches
à l’appel de la méthode d’instance.The static Matches
methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Matches
.
Le pattern
paramètre se compose d’éléments de langage d’expression régulière qui décrivent symboliquement la chaîne à faire correspondre.The pattern
parameter consists of regular expression language elements that symbolically describe the string to match. Pour plus d’informations sur les expressions régulières, consultez .NET Framework des expressions régulières et le langage des expressions régulières-aide-mémoire.For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.
La Matches méthode utilise l’évaluation paresseuse pour remplir l' MatchCollection objet retourné.The Matches method uses lazy evaluation to populate the returned MatchCollection object. L’accès aux membres de cette collection, MatchCollection.Count tels MatchCollection.CopyTo que et, entraîne le remplissage immédiat de la collection.Accessing members of this collection such as MatchCollection.Count and MatchCollection.CopyTo causes the collection to be populated immediately. Pour tirer parti de l’évaluation différée, vous devez effectuer une itération de la collection à foreach
l' C# aide For Each
d’une construction telle que dans et...Next
To take advantage of lazy evaluation, you should iterate the collection by using a construct such as foreach
in C# and For Each
…Next
en Visual Basic.in Visual Basic.
En raison de son évaluation différée, Matches l’appel de la méthode RegexMatchTimeoutException ne lève pas d’exception.Because of its lazy evaluation, calling the Matches method does not throw a RegexMatchTimeoutException exception. Toutefois, une exception est levée lorsqu’une opération est exécutée sur MatchCollection l’objet retourné par cette méthode, si une opération de correspondance dépasse cet intervalle de délai d’attentematchTimeout
spécifié par le paramètre.However, an exception is thrown when an operation is performed on the MatchCollection object returned by this method, if a matching operation exceeds this time-out interval specified by thematchTimeout
parameter.
Notes pour les appelants
Nous vous recommandons de définir le matchTimeout
paramètre sur une valeur appropriée, par exemple deux secondes.We recommend that you set the matchTimeout
parameter to an appropriate value, such as two seconds. Si vous désactivez les délais d' InfiniteMatchTimeoutattente en spécifiant, le moteur d’expression régulière offre des performances légèrement meilleures.If you disable time-outs by specifying InfiniteMatchTimeout, the regular expression engine offers slightly better performance. Toutefois, vous devez désactiver les délais d’expiration uniquement dans les conditions suivantes:However, you should disable time-outs only under the following conditions:
-Lorsque l’entrée traitée par une expression régulière est dérivée d’une source connue et approuvée ou se compose d’un texte statique.- When the input processed by a regular expression is derived from a known and trusted source or consists of static text. Cela exclut le texte qui a été saisi dynamiquement par les utilisateurs.This excludes text that has been dynamically input by users.
-Lorsque le modèle d’expression régulière a été minutieusement testé pour s’assurer qu’il gère efficacement les correspondances, les non-correspondances et les correspondances proches.- When the regular expression pattern has been thoroughly tested to ensure that it efficiently handles matches, non-matches, and near matches.
-Lorsque le modèle d’expression régulière ne contient aucun élément de langage connu pour provoquer une rétroaction excessive lors du traitement d’une correspondance proche.- When the regular expression pattern contains no language elements that are known to cause excessive backtracking when processing a near match.