"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
적이있을 것입니다 더 많거나 각'\ dy' 구분 사이 미만 2 개 공간 (첫 번째/마지막 것 제외)? – Servy
예, 변수가 될 수 있습니다 (일부는 사용자 입력이므로 두 개의 공백을 보장 할 수 없습니다 ...) – keynesiancross