同じ数字のみからなる文字列かどうか(正規表現)
文字列が "111" や "888888" のように全て同じ数字であるかを調べるプログラムです。 正規表現を使っています。
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; class Program { static void Main() { string[] tests = { "1", "11", "55", "5599999123", "a", "aa8888", "aaabdee", }; var re = new Regex(@"^(\d)\1*$"); foreach (string s in tests) { if (re.IsMatch(s)) { Console.WriteLine(" match:{0}", s); } else { Console.WriteLine("not match:{0}", s); } } } }
実行結果です。
match:1 match:11 match:55 not match:5599999123 not match:a not match:aa8888 not match:aaabdee