HIDORI on The Web

マネージコードしか書きたくない

文字列の中から数字だけ取り出すには?

without comments

ネタ元: 文字列の中から数字だけ取り出すには?

文字列に含まれた複数の数字列を取り出して連結。

もっと簡潔に…書けるかなぁ?


using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "あ1いう3え4お56789";

            Console.WriteLine(
                string.Concat(Regex.Matches(text, @"\d+").Cast().Select(_ => _.Value).ToArray()));
        }
    }
}

追記: 2010-06-04

Twitter でいくつかフィードバックを貰ったので、再考。

正規表現を使ってないので、この系統の方が性能的には有利なはず。

でも、char[] から string を得るのに string(char []) を使っているところが、ワンライナー的には許せないw

using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "あ1いう3え4お56789";

            Console.WriteLine(
                new string(text.Where(_ => char.IsDigit(_)).ToArray()));
        }
    }
}

さらに追記: 2010-06-04

お題を消化するだけならコレが最強w

^ による否定をすっかり忘れてたヨ…

あーんど、なんでもかんでも LINQ ろうと思ってはいけないね (^^;

using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "あ1いう3え4お56789";

            Console.WriteLine(
                Regex.Replace(text, @"[^\d]", string.Empty));
        }
    }
}

Written by Hiroaki SHIBUKI

6月 4th, 2010 at 10:37 am

Posted in 技術情報

Tagged with ,

Leave a Reply