5 正则表达式示例
如何:使用正则表达式分析字符串
下面的代码示例演示如何使用 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;
}
在C++.Net时,工程中需要包含两个文件vbscript.tli和vbscript.tlh。现在把这两个文件也一并传到资源里.