Rappresenta un'espressione regolare non modificabile.
Spazio dei nomi: System.Text.RegularExpressions
Assembly: System (in system.dll)
Visual Basic - (Dichiarazione)
<SerializableAttribute> _
Public Class Regex
Implements ISerializable
[SerializableAttribute]
public class Regex : ISerializable
[SerializableAttribute]
public ref class Regex : ISerializable
/** @attribute SerializableAttribute() */
public class Regex implements ISerializable
SerializableAttribute
public class Regex implements ISerializable
La classe Regex contiene numerosi metodi statici che consentono di utilizzare un'espressione regolare senza creare in modo esplicito un oggetto Regex. Utilizzare un metodo statico equivale a costruire un oggetto Regex, utilizzandolo una volta e poi distruggendolo.
La classe Regex è immutabile, ovvero è in sola lettura, ed è per definizione thread-safe. Gli oggetti Regex possono essere creati in qualsiasi thread e condivisi tra thread. Per ulteriori informazioni, vedere Protezione dei thread.
Nell'esempio di codice riportato di seguito viene illustrato come utilizzare un'espressione regolare per verificare se una stringa dispone del formato corretto per rappresentare un valore di valuta. Si noti l'utilizzo dei token di inclusione ^ e $ per indicare che è necessario che l'intera stringa, non solo una sottostringa, corrisponda all'espressione regolare.
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main ()
{
// Define a regular expression for currency values.
Regex rx = new Regex(@"^-?\d+(\.\d{2})?$");
// Define some test strings.
string[] tests = {"-42", "19.99", "0.001", "100 USD"};
// Check each test string against the regular expression.
foreach (string test in tests)
{
if (rx.IsMatch(test))
{
Console.WriteLine("{0} is a currency value.", test);
}
else
{
Console.WriteLine("{0} is not a currency value.", test);
}
}
}
}
#using <System.dll>
using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{
// Define a regular expression for currency values.
Regex^ rx = gcnew Regex( "^-?\\d+(\\.\\d{2})?$" );
// Define some test strings.
array<String^>^tests = {"-42","19.99","0.001","100 USD"};
// Check each test string against the regular expression.
System::Collections::IEnumerator^ myEnum = tests->GetEnumerator();
while ( myEnum->MoveNext() )
{
String^ test = safe_cast<String^>(myEnum->Current);
if ( rx->IsMatch( test ) )
{
Console::WriteLine( "{0} is a currency value.", test );
}
else
{
Console::WriteLine( "{0} is not a currency value.", test );
}
}
}
import System.*;
import System.Text.RegularExpressions.*;
public class Test
{
public static void main(String[] args)
{
// Define a regular expression for currency values.
Regex rx = new Regex("^-?\\d+(\\.\\d{2})?$");
// Define some test strings.
String tests[] = { "-42", "19.99", "0.001", "100 USD" };
// Check each test string against the regular expression.
for (int iCtr = 0; iCtr < tests.get_Length(); iCtr++) {
String test = (String)tests.get_Item(iCtr);
if (rx.IsMatch(test)) {
Console.WriteLine("{0} is a currency value.", test);
}
else {
Console.WriteLine("{0} is not a currency value.", test);
}
}
} //main
} //Test
Nell'esempio di codice riportato di seguito viene illustrato come utilizzare un'espressione regolare per individuare eventuali occorrenze ripetute di una parola all'interno di una stringa. Si noti l'utilizzo del costrutto (?<word>) per assegnare un nome a un gruppo e del costrutto (\k<word>) per fare riferimento a tale gruppo successivamente nell'espressione.
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main ()
{
// Define a regular expression for repeated words.
Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Define a test string.
string text = "The the quick brown fox fox jumped over the lazy dog dog.";
// Find matches.
MatchCollection matches = rx.Matches(text);
// Report the number of matches found.
Console.WriteLine("{0} matches found.", matches.Count);
// Report on each match.
foreach (Match match in matches)
{
string word = match.Groups["word"].Value;
int index = match.Index;
Console.WriteLine("{0} repeated at position {1}", word, index);
}
}
}
#using <System.dll>
using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{
// Define a regular expression for repeated words.
Regex^ rx = gcnew Regex( "\\b(?<word>\\w+)\\s+(\\k<word>)\\b",static_cast<RegexOptions>(RegexOptions::Compiled | RegexOptions::IgnoreCase) );
// Define a test string.
String^ text = "The the quick brown fox fox jumped over the lazy dog dog.";
// Find matches.
MatchCollection^ matches = rx->Matches( text );
// Report the number of matches found.
Console::WriteLine( "{0} matches found.", matches->Count );
// Report on each match.
for each (Match^ match in matches)
{
String^ word = match->Groups["word"]->Value;
int index = match->Index;
Console::WriteLine("{0} repeated at position {1}", word, index);
}
}
import System.*;
import System.Text.RegularExpressions.*;
public class Test
{
public static void main(String[] args)
{
// Define a regular expression for repeated words.
Regex rx = new Regex("\\b(?<word>\\w+)\\s+(\\k<word>)\\b",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Define a test string.
String text = "The the quick brown fox fox jumped over the "
+ "lazy dog dog.";
// Find matches.
MatchCollection matches = rx.Matches(text);
// Report the number of matches found.
Console.WriteLine("{0} matches found.", (Int32)matches.get_Count());
// Report on each match.
for (int iCtr = 0; iCtr < matches.get_Count(); iCtr++) {
Match match = matches.get_Item(iCtr);
String word = match.get_Groups().get_Item("word").get_Value();
int index = match.get_Index();
Console.WriteLine("{0} repeated at position {1}", word,
(Int32)index);
}
} //main
} //Test
Gerarchia di ereditarietà
System.Object
System.Text.RegularExpressions.Regex
Classi derivate
I membri statici pubblici (Shared in Visual Basic) di questo tipo sono validi per le operazioni multithreading. I membri di istanza non sono garantiti come thread safe.
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile per Pocket PC, Windows Mobile per Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema.
Informazioni sulla versione
.NET Framework
Supportato in: 2.0 1.1 1.0
.NET Compact Framework
Supportato in: 2.0 1.0