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

本文关键字:正则表达式 | 更新日期: 2023-09-27 18:35:54

我有一个程序,它必须使用正则表达式输出精确长度的子字符串。但它也会输出更大长度的子字符串,这些子字符串与格式匹配。输入:A 作为 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);
        }
    }
}

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

'b 添加到表达式中,意思是"在单词的开头或结尾",例如:

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

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

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

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