C#正则表达式的确切长度

时间:2012-06-01 08:57:27

标签: c# regex

我有一个程序,必须使用regexp输出精确长度的子串。 但它也输出更长的子串,匹配格式。 输入: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);
        }
    }
}

1 个答案:

答案 0 :(得分:4)

\b添加到您的表达式中,这意味着“在单词的开头或结尾”,例如:

\b[a-zA-Z]{3}\b

在您的代码中,您应该执行以下操作:

String regFormat = @"\b[a-zA-Z]{" + count.ToString() + @"}\b";

要在编写自己的测试程序之前测试正则表达式,可以使用ExpressoThe Regulator等工具。它们实际上可以帮助您编写表达式并对其进行测试。