UnknitSplash
UnknitSplash

Reputation: 65

C# regex exact length

I have a program, that has to output substrings of exact length using regexp. But it outputs also substrings of a greater length, which match format. input: a as asb, asd asdf asdfg expected output(with length = 3): asb asd real output: 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);
        }
    }
}

Upvotes: 3

Views: 16825

Answers (1)

Paolo Tedesco
Paolo Tedesco

Reputation: 57182

Add \b, which means "at beginning or end of a word", to your expression, for example:

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

In your code you should do the following:

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

To test regular expression before coding your own test program, you can use tools like Expresso or The Regulator. They actually help you writing the expression and test it.

Upvotes: 6

Related Questions