2012-07-11 3 views
1

다음과 같은 문자열이 있습니다. "1y 250 2y 32 % 3y otherjibberish". "1Y 250" "2Y 32 %" "otherjibberish 3Y"Regex를 사용하여 여러 일치 항목간에 내용 분리

이러한 분할의 주요 '분리기'는 \ "의 D + Y 같습니다

내 최종 목표는 다음으로 분할하는 "패턴. Regex (C# 4.0)을 사용하면 Matches 함수를 사용하여 'y'가 뒤에 오는 숫자와 일치시킬 수 있지만 그 일치를 따르지만 다음 일치를 앞서는 모든 것을 얻는 방법을 알지 못합니다.

할 방법이 있습니까? 의미가

희망이 .... 많은 평가 - kcross

+0

적이있을 것입니다 더 많거나 각'\ dy' 구분 사이 미만 2 개 공간 (첫 번째/마지막 것 제외)? – Servy

+0

예, 변수가 될 수 있습니다 (일부는 사용자 입력이므로 두 개의 공백을 보장 할 수 없습니다 ...) – keynesiancross

답변

2

"MatchCollection"을 사용하여 어커런스에 따라 문자열을 분할 할 수 있습니다. 아래 예는 원하는 것을 거의 수행합니다. 각 문자열의 오른쪽에있는 공백 문자는 제거되지 않습니다.

코드 :

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Text.RegularExpressions; 

namespace Q11438740ConApp 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string sourceStr = "1y 250 2y 32% 3y otherjibberish"; 
      Regex rx = new Regex(@"\d+y"); 
      string[] splitedArray = SplitByRegex(sourceStr, rx); 

      for (int i = 0; i < splitedArray.Length; i++) 
      { 
       Console.WriteLine(String.Format("'{0}'", splitedArray[i])); 
      } 

      Console.ReadLine(); 
     } 

     public static string[] SplitByRegex(string input, Regex rx) 
     { 
      MatchCollection matches = rx.Matches(input); 
      String[] outArray = new string[matches.Count]; 
      for (int i = 0; i < matches.Count; i++) 
      { 
       int length = 0; 
       if (i == matches.Count - 1) 
       { 
        length = input.Length - (matches[i].Index + matches[i].Length); 
       } 
       else 
       { 
        length = matches[i + 1].Index - (matches[i].Index + matches[i].Length); 
       } 

       outArray[i] = matches[i].Value + input.Substring(matches[i].Index + matches[i].Length, length); 
      } 

      return outArray; 
     } 
    } 
} 

출력 :

'1y 250 ' 
'2y 32% ' 
'3y otherjibberish' 

"솔루션"7Z 파일 : Q11438740ConApp.7z

0

을이 그냥 Regex.Split() 메소드를 사용 ... 사실은 꽤 쉬웠다.

+0

참고 : 분할하면 숫자 값이 손실됩니다 ('{ "250 당신은 순서를 추론 할 수 있지만 순서가 매겨지지 않은 요소는 문제가 될 것입니다. – James

+0

분할을하기 위해 어떤 패턴을 사용합니까? 내가 그것을 할 때 숫자가 남아 있습니다. – keynesiancross

+0

내 콘솔 앱이 보입니다. \t \t \t 문자열 입력 = "otherjibberish 1Y 250 2Y 32 % 3Y」; regex.Split에 \t \t \t의 foreach (문자열들 (입력이 '정규식 정규식 = 새로운 정규식 (@"\ D + Y ") 등)) { \t \t \t \t Console.WriteLine ("Item :"+ s); \t \t \t} – James

관련 문제