shuhelohelo’s blog

Xamarin.Forms多めです.

正規表現でマッチした部分を同じ文字数の記号で置換する

実装の一例としてメモ

例えば,連続する半角スペースに対して2文字目以降をnbspで置き換える場合は以下のようにする.

        public static string ConsecutiveBlanksToNBSP(string sentense)
        {
            Regex re = new Regex(@"(?<= )( )+");
            MatchCollection matches = re.Matches(sentense);

            if (matches.Count == 0)
            {
                Console.WriteLine("nothing");
                return sentense;
            }

            var strBuilder = new StringBuilder(sentense);
            foreach (Match m in matches)
            {
                strBuilder.Remove(m.Index, m.Length);//対象部分を削除
                strBuilder.Insert(m.Index, new string('\u00a0', m.Length));//挿入
            }

            return strBuilder.ToString();
        }