입력받은 문자열에서 숫자만 추출하기 (Regex클래스)

2017. 2. 1. 16:53C# 윈폼 ( Windows Forms )/TextBox

1. MSDN

Regex클래스


2. 입력받은 문자열에서 숫자만 출력하기 예제

   -1) 다음과 같이 GUI를 구성합니다.

   -2) 각 컨트롤의 ID를 설정합니다.


Label : lab_Regex_1, lab_Regex_2

TextBox : tb_1_1, tb_1_2, tb_2_1, tb_2_2, tb_3_1, tb_3_2, tb_4_1, tb_4_2

Button : btn_Regex




   -3) Button의 클릭이벤트를 추가합니다.


클릭이벤트명 : btn_Regex_Click

 



   -4) 프로그램을 실행했을 때 값을 출력하는 코드를 작성합니다.

      -> public Form1()에서 tb_Clear() 메소드를 호출합니다.

      -> tb_Clear()메소드는 TextBox에 값을 출력합니다.

 

        public Form1()

        {

            InitializeComponent();

            tb_Clear();

        }


        private void tb_Clear()

        {

            tb_1_1.Text = "2017.02.01";

            tb_2_1.Text = "17-02-01";

            tb_3_1.Text = "2017년02월01일";

            tb_4_1.Text = "17 02 01";

        }



   -5) TextBox에 값이 출려된 실행화면


   -6) Button의 클릭이벤트의 코드를 작성합니다.


        private void btn_Regex_Click(object sender, EventArgs e)

        {

            string StrTemp1 = Regex.Replace(tb_1_1.Text, @"\D", "");

            string StrTemp2 = Regex.Replace(tb_2_1.Text, @"\D", "");

            string StrTemp3 = Regex.Replace(tb_3_1.Text, @"\D", "");

            string StrTemp4 = Regex.Replace(tb_4_1.Text, @"\D", "");


            tb_1_2.Text = StrTemp1;

            tb_2_2.Text = StrTemp2;

            tb_3_2.Text = StrTemp3;

            tb_4_2.Text = StrTemp4;

        }

 


   -7) Regex 클래스를 사용하기 위해 참조를 합니다.


using System.Text.RegularExpressions;

 


   -8) 프로그램을 실행한 후 추출버튼을 클릭하면 숫자만 추출되어 출력된 것을 확인할 수 있습니다.