2012-06-01 2 views
2

정규식을 사용하여 정확한 길이의 부분 문자열을 출력해야하는 프로그램이 있습니다. 그러나 더 큰 길이의 하위 문자열도 출력하므로 형식이 일치합니다. 입력 : 단어의 시작 또는 끝에서 "수단 ASB ASD ASD ASDC# regex exact length

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

답변

5

\b 추가 : ASB ASD 실제 출력 (길이 = 3)와 ASB 등, ASD 자위대 asdfg 예상 출력 "당신의 표현, 예를 들어 :

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

:

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

코드에서는 다음을 수행해야합니다 자신의 테스트 프로그램을 코딩하기 전에 정규식을 테스트하려면 Expresso 또는 The Regulator과 같은 도구를 사용할 수 있습니다. 그들은 실제로 표현을 작성하고 테스트하는 것을 도와줍니다.

+0

특정 번호 (예 : 3)를 설정하면 작동합니다. 그러나 그것은 count와 함께 작동하지 않습니다 .ToString() – UnknitSplash

+0

예, 이것은 3의 경우에 대한 예였습니다. 이전에했던 것처럼 문자열을 연결하는 표현식을 만들어야합니다. 업데이트 된 답변보기 –

+0

고마워요! =) – UnknitSplash