title | ms.custom | ms.date | ms.reviewer | ms.suite | ms.technology | ms.tgt_pltfrm | ms.topic | dev_langs | helpviewer_keywords | ms.assetid | caps.latest.revision | author | ms.author | manager | ||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
How to: Use Regular Expressions to Rearrange Data (C++/CLI) | Microsoft Docs |
11/04/2016 |
|
article |
|
|
5f91e777-9471-424e-ba75-dca3d1b49e42 |
9 |
mikeblome |
mblome |
ghogen |
The following code example demonstrates how the .NET Framework regular expression support can be used to rearrange, or reformat data. The following code example uses the xref:System.Text.RegularExpressions.Regex and xref:System.Text.RegularExpressions.Match classes to extract first and last names from a string and then display these name elements in reverse order.
The xref:System.Text.RegularExpressions.Regex class is used to construct a regular expression that describes the current format of the data. The two names are assumed to be separated by a comma and can use any amount of white-space around the comma. The xref:System.Text.RegularExpressions.Match method is then used to analyze each string. If successful, first and last names are retrieved from the xref:System.Text.RegularExpressions.Match object and displayed.
// regex_reorder.cpp
// compile with: /clr
#using <System.dll>
using namespace System;
using namespace Text::RegularExpressions;
int main()
{
array<String^>^ name =
{
"Abolrous, Sam",
"Berg,Matt",
"Berry , Jo",
"www.contoso.com"
};
Regex^ reg = gcnew Regex("(?<last>\\w*)\\s*,\\s*(?<first>\\w*)");
for ( int i=0; i < name->Length; i++ )
{
Console::Write( "{0,-20}", name[i] );
Match^ m = reg->Match( name[i] );
if ( m->Success )
{
String^ first = m->Groups["first"]->Value;
String^ last = m->Groups["last"]->Value;
Console::WriteLine("{0} {1}", first, last);
}
else
Console::WriteLine("(invalid)");
}
return 0;
}
.NET Framework Regular Expressions
.NET Programming with C++/CLI (Visual C++)