모든 프로그래밍 언어는 정규식(regular expression)을 지원합니다.
정규식은 간단히 말해 문자열에서 특정 패턴을 찾아 주는 기능입니다.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Code_practice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static void Main()
{
string s = "안녕하세요. 반갑습니다. 또 만나요.";
var regex = new Regex("\\\\s+"); // 하나 이상의 공백 패턴 검사
string r = regex.Replace(s, " "); // 하나 이상의 공백을 공백 하나로 변환
Console.WriteLine(s);
Console.WriteLine(r);
}
}
}
// 출력
// 안녕하세요. 반갑습니다. 또 만나요.
// 안녕하세요. 반갑습니다. 또 만나요.
Regex 클래스의 생성자에 전달된 \s 기호는 공백 문자를 의미합니다. 즉, 하나 이상의 공백 문자를 검사해서 공백 하나로 변환하는 코드 입니다.
특정 문자열이 이메일 형태인지 검사하는 예제
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Code_practice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static void Main()
{
string email = "[email protected]";
Console.WriteLine(IsEmail(email);
}
static bool IsEmail(string email)
{
bool result = false;
// 이메일을 검사하는 정규식은 인터넷에서 검색하여 사용 가능
Regex regex = new Regex("/ ^[0 - 9a - zA - Z]([-_.]?[0 - 9a - zA - Z]) *@[0 - 9a - zA - Z]([-_.]?[0 - 9a - zA - Z]) *.[a - zA - Z]{ 2,3}$/ i");
result = regex.IsMatch(email);
return result;
}
}
}
// 결과
// true