Regex.GroupNameFromNumber(Int32) Método
Definição
Obtém o nome do grupo que corresponde ao número do grupo especificado.Gets the group name that corresponds to the specified group number.
public:
System::String ^ GroupNameFromNumber(int i);
public string GroupNameFromNumber (int i);
member this.GroupNameFromNumber : int -> string
Public Function GroupNameFromNumber (i As Integer) As String
Parâmetros
- i
- Int32
O número do grupo a ser convertido para o nome de grupo correspondente.The group number to convert to the corresponding group name.
Retornos
Uma cadeia de caracteres que contém o nome de grupo associado ao número de grupo especificado.A string that contains the group name associated with the specified group number. Se não houver nenhum nome de grupo que corresponda a i, o método retornará Empty.If there is no group name that corresponds to i, the method returns Empty.
Exemplos
O exemplo a seguir define um padrão de expressão regular que corresponde a uma linha de endereço que contém um nome de cidade dos EUA, um nome de estado e um CEP.The following example defines a regular expression pattern that matches an address line containing a U.S. city name, state name, and zip code. O exemplo usa o GroupNameFromNumber método para recuperar os nomes dos grupos de captura.The example uses the GroupNameFromNumber method to retrieve the names of capturing groups. Em seguida, ele usa esses nomes para recuperar os grupos capturados correspondentes para correspondências.It then uses these names to retrieve the corresponding captured groups for matches.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"(?<city>[A-Za-z\s]+), (?<state>[A-Za-z]{2}) (?<zip>\d{5}(-\d{4})?)";
string[] cityLines = {"New York, NY 10003", "Brooklyn, NY 11238", "Detroit, MI 48204",
"San Francisco, CA 94109", "Seattle, WA 98109" };
Regex rgx = new Regex(pattern);
List<string> names = new List<string>();
int ctr = 1;
bool exitFlag = false;
// Get group names.
do {
string name = rgx.GroupNameFromNumber(ctr);
if (! String.IsNullOrEmpty(name))
{
ctr++;
names.Add(name);
}
else
{
exitFlag = true;
}
} while (! exitFlag);
foreach (string cityLine in cityLines)
{
Match match = rgx.Match(cityLine);
if (match.Success)
Console.WriteLine("Zip code {0} is in {1}, {2}.",
match.Groups[names[3]],
match.Groups[names[1]],
match.Groups[names[2]]);
}
}
}
// The example displays the following output:
// Zip code 10003 is in New York, NY.
// Zip code 11238 is in Brooklyn, NY.
// Zip code 48204 is in Detroit, MI.
// Zip code 94109 is in San Francisco, CA.
// Zip code 98109 is in Seattle, WA.
Imports System.Collections.Generic
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "(?<city>[A-Za-z\s]+), (?<state>[A-Za-z]{2}) (?<zip>\d{5}(-\d{4})?)"
Dim cityLines() As String = {"New York, NY 10003", "Brooklyn, NY 11238", "Detroit, MI 48204", _
"San Francisco, CA 94109", "Seattle, WA 98109" }
Dim rgx As New Regex(pattern)
Dim names As New List(Of String)
Dim ctr As Integer = 1
Dim exitFlag As Boolean = False
' Get group names.
Do
Dim name As String = rgx.GroupNameFromNumber(ctr)
If Not String.IsNullOrEmpty(name) Then
ctr += 1
names.Add(name)
Else
exitFlag = True
End If
Loop While Not exitFlag
For Each cityLine As String In cityLines
Dim match As Match = rgx.Match(cityLine)
If match.Success Then
Console.WriteLine("Zip code {0} is in {1}, {2}.", _
match.Groups.Item(names.Item(3)), _
match.Groups.Item(names.Item(1)), _
match.Groups.Item(names.Item(2)))
End If
Next
End Sub
End Module
' The example displays the following output:
' Zip code 10003 is in New York, NY.
' Zip code 11238 is in Brooklyn, NY.
' Zip code 48204 is in Detroit, MI.
' Zip code 94109 is in San Francisco, CA.
' Zip code 98109 is in Seattle, WA.
O padrão de expressão regular é definido pela seguinte expressão:The regular expression pattern is defined by the following expression:
(?<city>[A-Za-z\s]+), (?<state>[A-Za-z]{2}) (?<zip>\d{5}(-\d{4})?)
A tabela a seguir mostra como o padrão da expressão regular é interpretado.The following table shows how the regular expression pattern is interpreted.
| PadrãoPattern | DescriçãoDescription |
|---|---|
(?<city>[A-Za-z\s]+) |
Corresponder um ou mais caracteres alfabéticos ou de espaço em branco.Match one or more alphabetic or white-space character. Atribua o nome deste grupo capturado city .Assign this captured group the name city. |
, |
Corresponder uma vírgula (,) seguida por um caractere de espaço em branco.Match a comma (,) followed by a white-space character. |
(?<state>[A-Za-z]{2}) |
Corresponder dois caracteres alfabéticos.Match two alphabetic characters. Atribua o nome deste grupo capturado state .Assign this captured group the name state. Esse grupo deve ser seguido por um caractere de espaço em branco.This group should be followed by a white-space character. |
(?<zip>\d{5}(-\d{4})?) |
Corresponde a cinco dígitos numéricos seguidos por zero ou uma ocorrência de um hífen seguido de quatro dígitos.Match five numeric digits followed by either zero or one occurrence of a hyphen followed by four digits. Atribua o nome deste grupo capturado zip .Assign this captured group the name zip. |
Comentários
Um padrão de expressão regular pode conter grupos de captura nomeados ou numerados, que delineam subexpressãos dentro de uma correspondência de padrão.A regular expression pattern may contain either named or numbered capturing groups, which delineate subexpressions within a pattern match. Os grupos numerados são delimitados pela sintaxe (subexpressão) e recebem números com base em sua ordem na expressão regular.Numbered groups are delimited by the syntax (subexpression) and are assigned numbers based on their order in the regular expression. Os grupos nomeados são delimitados pela sintaxe (? < nome > do subexpressão) ou (? " Name'subexpression), em que Name é o nome pelo qual a subexpressão será identificada.Named groups are delimited by the syntax (?<name>subexpression) or (?'name'subexpression), where name is the name by which the subexpression will be identified. (Para obter mais informações, consulte agrupando construções.) O GroupNameFromNumber método identifica os grupos nomeados e os grupos numerados por suas posições ordinais na expressão regular.(For more information, see Grouping Constructs.) The GroupNameFromNumber method identifies both named groups and numbered groups by their ordinal positions in the regular expression. A posição ordinal zero sempre representa a expressão regular inteira.Ordinal position zero always represents the entire regular expression. Todos os grupos numerados são então contados antes de grupos nomeados, independentemente da sua posição real no padrão de expressão regular.All numbered groups are then counted before named groups, regardless of their actual position in the regular expression pattern.
Se i for o número de um grupo nomeado, o método retornará o nome do grupo.If i is the number of a named group, the method returns the name of the group. Se i for o número de um grupo sem nome, o método retornará a representação de cadeia de caracteres do número.If i is the number of an unnamed group, the method returns the string representation of the number. Por exemplo, se i for 1, o método retornará "1".For example, if i is 1, the method returns "1". Se i não for o número de um grupo de captura, o método retornará String.Empty .If i is not the number of a capturing group, the method returns String.Empty.
Se for encontrada uma correspondência de padrão, o valor retornado por esse método poderá ser usado para recuperar o Group objeto que representa o grupo capturado da GroupCollection.Item[] propriedade.If a pattern match is found, the value returned by this method can then be used to retrieve the Group object that represents the captured group from the GroupCollection.Item[] property. O GroupCollection objeto é retornado pela Match.Groups propriedade.The GroupCollection object is returned by the Match.Groups property.