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);
        }
    }
}
4

1 に答える 1

6

\b「単語の先頭または末尾」を意味する を式に追加します。次に例を示します。

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

コードでは、次のことを行う必要があります。

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

独自のテスト プログラムをコーディングする前に正規表現をテストするには、ExpressoThe Regulatorなどのツールを使用できます。それらは実際に式を記述してテストするのに役立ちます。

于 2012-06-01T09:05:42.070 に答える