我有一个程序,它必须使用正则表达式输出精确长度的子字符串。但它也会输出与格式匹配的更大长度的子字符串。输入:a as asb, asd asdf asdfg 预期输出(长度 = 3):asb asd 实际输出:asb asd asd asd
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace LR3_2
{
class Program
{
static void regPrint(String input, int count)
{
String regFormat = @"[a-zA-Z]{" + count.ToString() + "}";
Regex reg = new Regex(regFormat);
foreach (var regexMatch in reg.Matches(input))
{
Console.Write(regexMatch + " ");
}
//Match matchObj = reg.Match(input);
//while (matchObj.Success)
//{
// Console.Write(matchObj.Value + " ");
// matchObj = reg.Match(input, matchObj.Index + 1);
//}
}
static void Main(string[] args)
{
String input = " ";
//Console.WriteLine("Enter string:");
//input = Console.ReadLine();
//Console.WriteLine("Enter count:");
//int count = Console.Read();
input += "a as asb, asd asdf asdfg";
int count = 3;
regPrint(input, count);
}
}
}