正则表达式 (C++/CLI)
演示在 .NET Framework 中使用正则表达式类进行的各种字符串操作。
以下主题演示使用 .NET Framework System.Text.RegularExpressions 命名空间(在某种情况下是还要使用 System.String.Split 方法)来搜索、分析和修改字符串。
使用正则表达式分析字符串
下面的代码示例演示使用 System.Text.RegularExpressions 命名空间中的 Regex 类进行简单的字符串分析。 构造包含多种类型单词分隔符的字符串。 然后使用 Regex 类与 Match 类一起分析字符串。 然后,句子中每个单词都会单独显示。
示例
// regex_parse.cpp
// compile with: /clr
#using <system.dll>
using namespace System;
using namespace System::Text::RegularExpressions;
int main( )
{
int words = 0;
String^ pattern = "[a-zA-Z]*";
Console::WriteLine( "pattern : '{0}'", pattern );
Regex^ regex = gcnew Regex( pattern );
String^ line = "one\ttwo three:four,five six seven";
Console::WriteLine( "text : '{0}'", line );
for( Match^ match = regex->Match( line );
match->Success; match = match->NextMatch( ) )
{
if( match->Value->Length > 0 )
{
words++;
Console::WriteLine( "{0}", match->Value );
}
}
Console::WriteLine( "Number of Words : {0}", words );
return 0;
}
使用 Split 方法分析字符串
下面的代码示例演示使用 System.String.Split 方法从字符串中提取每个单词。 构造包含多种类型单词分隔符的字符串,然后在分隔符列表中通过调用 Split 分析此字符串。 然后,句子中每个单词都会单独显示。
示例
// regex_split.cpp
// compile with: /clr
using namespace System;
int main()
{
String^ delimStr = " ,.:\t";
Console::WriteLine( "delimiter : '{0}'", delimStr );
array<Char>^ delimiter = delimStr->ToCharArray( );
array<String^>^ words;
String^ line = "one\ttwo three:four,five six seven";
Console::WriteLine( "text : '{0}'", line );
words = line->Split( delimiter );
Console::WriteLine( "Number of Words : {0}", words->Length );
for (int word=0; word<words->Length; word++)
Console::WriteLine( "{0}", words[word] );
return 0;
}
将正则表达式用于简单匹配
下面的代码示例使用正则表达式查找确切的子字符串匹配项。 搜索由静态 IsMatch 方法执行,该方法将两个字符串作为输入。 第一个是要搜索的字符串,第二个是要搜索的模式。
示例
// regex_simple.cpp
// compile with: /clr
#using <System.dll>
using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{
array<String^>^ sentence =
{
"cow over the moon",
"Betsy the Cow",
"cowering in the corner",
"no match here"
};
String^ matchStr = "cow";
for (int i=0; i<sentence->Length; i++)
{
Console::Write( "{0,24}", sentence[i] );
if ( Regex::IsMatch( sentence[i], matchStr,
RegexOptions::IgnoreCase ) )
Console::WriteLine(" (match for '{0}' found)", matchStr);
else
Console::WriteLine("");
}
return 0;
}
使用正则表达式提取数据字段
下面的代码示例演示如何使用正则表达式从格式化字符串中提取数据。 下面的代码示例使用 Regex 类指定与电子邮件地址对应的模式。 此模式包括可用于检索每个电子邮件地址的用户名和主机名部分的字段标识符。 Match 类用于执行实际的模式匹配。 如果给定的电子邮件地址有效,则会提取并显示用户名和主机名。
示例
// Regex_extract.cpp
// compile with: /clr
#using <System.dll>
using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{
array<String^>^ address=
{
"jay@southridgevideo.com",
"barry@adatum.com",
"treyresearch.net",
"karen@proseware.com"
};
Regex^ emailregex = gcnew Regex("(?<user>[^@]+)@(?<host>.+)");
for (int i=0; i<address->Length; i++)
{
Match^ m = emailregex->Match( address[i] );
Console::Write("\n{0,25}", address[i]);
if ( m->Success )
{
Console::Write(" User='{0}'",
m->Groups["user"]->Value);
Console::Write(" Host='{0}'",
m->Groups["host"]->Value);
}
else
Console::Write(" (invalid email address)");
}
Console::WriteLine("");
return 0;
}
使用正则表达式重新排列数据
下面的代码示例演示如何使用 .NET Framework 正则表达式支持来重新排列或重新格式化数据。 下面的代码示例使用 Regex 和 Match 类从字符串中提取名字和姓氏,然后按相反顺序显示这些名称元素。
Regex 类用于构造描述数据当前格式的正则表达式。 假定这两个名称用逗号分隔,并且可以在逗号周围使用任意数量的空格。 然后使用 Match 方法分析每个字符串。 如果成功,名字和姓氏将从 Match 对象中检索得到并显示出来。
示例
// 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;
}
使用正则表达式进行搜索和替换
下面的代码示例演示如何使用正则表达式类 Regex 进行搜索和替换。 此操作通过 Replace 方法完成。 使用的版本将两个字符串作为输入:要修改的字符串,以及要插入的字符串以代替与给定 Regex 对象的模式匹配的部分(如果有)。
此代码用下划线 (_) 替换字符串中所有数字,然后再用空字符串替换字,从而有效地删除它们。 可在一个步骤中实现相同效果,但此处使用两个步骤进行演示。
示例
// regex_replace.cpp
// compile with: /clr
#using <System.dll>
using namespace System::Text::RegularExpressions;
using namespace System;
int main()
{
String^ before = "The q43uick bro254wn f0ox ju4mped";
Console::WriteLine("original : {0}", before);
Regex^ digitRegex = gcnew Regex("(?<digit>[0-9])");
String^ after = digitRegex->Replace(before, "_");
Console::WriteLine("1st regex : {0}", after);
Regex^ underbarRegex = gcnew Regex("_");
String^ after2 = underbarRegex->Replace(after, "");
Console::WriteLine("2nd regex : {0}", after2);
return 0;
}
使用正则表达式验证数据格式
下面的代码示例演示如何使用正则表达式来验证字符串的格式。 在下面的代码示例中,字符串应包含有效的电话号码。 下面的代码示例使用字符串“\d{3}-\d{3}-\d{4}”指示每个字段代表一个有效的电话号码。 字符串中的“d”表示一个数字,每个“d”后面的参数表示必需的数字位数。 在这种情况下,需要用短划线分隔数字。
示例
// regex_validate.cpp
// compile with: /clr
#using <System.dll>
using namespace System;
using namespace Text::RegularExpressions;
int main()
{
array<String^>^ number =
{
"123-456-7890",
"444-234-22450",
"690-203-6578",
"146-893-232",
"146-839-2322",
"4007-295-1111",
"407-295-1111",
"407-2-5555",
};
String^ regStr = "^\\d{3}-\\d{3}-\\d{4}$";
for ( int i = 0; i < number->Length; i++ )
{
Console::Write( "{0,14}", number[i] );
if ( Regex::IsMatch( number[i], regStr ) )
Console::WriteLine(" - valid");
else
Console::WriteLine(" - invalid");
}
return 0;
}