Skip to content

Instantly share code, notes, and snippets.

@skysan87
Last active January 22, 2019 13:53
Show Gist options
  • Save skysan87/350a86ae2631aee6a1194516649b72da to your computer and use it in GitHub Desktop.
Save skysan87/350a86ae2631aee6a1194516649b72da to your computer and use it in GitHub Desktop.
Split text using by Regular-Expressions
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace sampleapp_csharp
{
class Program
{
// 正規表現で取得した文字列で分割する
static void Main(string[] args)
{
var testWords = "2525dddd129083471sdfajlskf98572";
var pattern = "d{1,3}";
var matches = Regex.Matches(testWords, pattern);
var array = new List<string>();
int charIndex = 0;
for (int i = 0; i < matches.Count; i++)
{
// 一致した値より前方の文字を切り出す
if (matches[i].Index > charIndex)
{
array.Add(testWords.Substring(charIndex, matches[i].Index - charIndex));
}
// 一致した値を保存
array.Add(matches[i].Value);
// 次の切り出しの始まり
charIndex = matches[i].Index + matches[i].Length;
// 最後の場合、一致した値よりの後方に文字があれば切り出す
if ((i == matches.Count - 1)
&& (matches[i].Index + matches[i].Length < testWords.Length))
{
array.Add(testWords.Substring(charIndex, testWords.Length - charIndex));
}
}
array.ForEach(Console.WriteLine);
// Result:
// 2525
// ddd
// d
// 129083471s
// d
// fajlskf98572
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment