Console.WriteLine("请输入截止数字?退出请输入y"); string input = Console.ReadLine(); int n = Convert.ToInt32(input); int count = 0; //计数 for (int i = 0; i <= n; i++) { string str = i.ToString();//要匹配的字符串 string pattern="1"; //要匹配的正则表达式模式 MatchCollection matches = Regex.Matches(str, pattern); //正则表达式匹配验证 count += matches.Count; //获得匹配数量,加到计数上, //foreach (Match NextMatch in matches) //遍历获得数量也行,不过效率低 //{ // count++; //} } Console.WriteLine("在0-{0}中1出现了"+count+"次",input);