C# 正则表达式精确长度

3

我有一个程序,需要使用正则表达式输出精确长度的子字符串。 但是它也会输出匹配格式的更长子字符串。 输入: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个回答

6

在你的表达式中添加 \b,表示“单词的开头或结尾”,例如:

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

在你的代码中,你应该执行以下步骤:
String regFormat = @"\b[a-zA-Z]{" + count.ToString() + @"}\b";

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


如果我设置特定的数字(比如3)- 它可以工作。但是使用count.ToString()就不行了。 - UnknitSplash
是的,这只是针对3的情况的示例,然后您必须像以前一样创建连接字符串的表达式。请参见更新的答案。 - Paolo Tedesco
@UnknitSplash:使用 count.ToString() 是可以的。你的代码怎么样?你有没有不小心忘记在字符串的最后一个部分前加上 @ 符号? - Paolo Tedesco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接