C# - How To Use Regular Expressions ( Regex ) In C#
-email.
-url.
-phone number.
-birthday.
Source code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
public partial class Regex_Form : Form
{
public Regex_Form()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// mail@mail.com => ^([\w]+)@([\w]+)\.([\w]+)$
// http://www.google.com => ^(http://www\.)([\w]+)\.([\w]+)$
// Phone Number like : 0011 XXX XXX XXX => ^(0011)(([ ][0-9]{3}){3})$
// Date XX/XX/XXXX => ^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$
Regexp(@"^([\w]+)@([\w]+)\.([\w]+)$",textBox1, pictureBox1, lblemail, "Mail");
Regexp(@"^(http://www\.)([\w]+)\.([\w]+)$", textBox2, pictureBox2, lblwebsite, "Web Site");
Regexp(@"^(0011)(([ ][0-9]{3}){3})$", textBox3, pictureBox3, lblphone, "Phone Number");
Regexp(@"^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$", textBox4, pictureBox4, lbldate, "Date");
}
public void Regexp(string re, TextBox tb, PictureBox pc, Label lbl, string s)
{
Regex regex = new Regex(re);
if(regex.IsMatch(tb.Text))
{
pc.Image = Properties.Resources.valid;
lbl.ForeColor = Color.Green;
lbl.Text = s + " Valid";
}
else
{
pc.Image = Properties.Resources.invalid;
lbl.ForeColor = Color.Red;
lbl.Text = s + " InValid";
}
}
}
}
=> OutPut :
C# Regex |
Download Projects Source Code