学习C#里的正则表达式
小生初学编程,看了javascript的正则,但很少有介绍c#的。其实和其他语言也差不多,没有啥大同小异
http://msdn.microsoft.com/zh-cn/library/30wbz966(v=VS.85).aspx 这上面讲的不错
首先是单个匹配
// Create a new Regex object.
Regex r = new Regex("abc");
// Find a single match in the string.
Match m = r.Match("123abc456");
if (m.Success)
{
// Print out the character position where a match was found.
// (Character position 3 in this case.)
Console.WriteLine("Found match at position " + m.Index);
Console.WriteLine("Found:" + m.ToString());
}
多个匹配,用的是集合类型
MatchCollection mc;
String[] results = new String[20];
int[] matchposition = new int[20];
// Create a new Regex object and define the regular expression.
Regex r = new Regex("abc");
// Use the Matches method to find all matches in the input string.
mc = r.Matches("123abc4abcd");
// Loop through the match collection to retrieve all
// matches and positions.
for (int i = 0; i < mc.Count; i++)
{
// Add the match string to the string array.
results[i] = mc[i].Value;
// Record the character position where the match was found.
matchposition[i] = mc[i].Index;
}