Showing posts with label Regular Expressions. Show all posts
Showing posts with label Regular Expressions. Show all posts

Wednesday, January 16, 2013

Regular Expression Examples

*     
Zero or more occurrences of the previous character or subexpression. For example, 7*8 matches   7778 or just 8.

+ 
One or more occurrences of the previous character or subexpression. For example, 7+8 matches 7778 but not 8.

( ) 
Groups a subexpression that will be treated as a single element. For example, (78)+ matches 78 and 787878.

{m,n} 
The previous character (or subexpression) can occur from m to n times. For example, A{1,3} matches A, AA, or AAA.

| 
Either of two matches. For example, 8|6 matches 8 or 6.

[ ] 
Matches one character in a range of valid characters. For example, [A-C] matches A, B, or C.

[^ ] 
Matches a character that isn’t in the given range. For example, [^A-B] matches any character except A and B.

. 
Any character except newline. For example, .here matches where and there.

\s 
Any whitespace character (such as a tab or space).

\S 
Any nonwhitespace character.

\d 
Any digit character.

\D 
Any character that isn’t a digit.

\w 
Any “word” character (letter, number, or underscore).

\W 
Any character that isn’t a “word” character (letter, number, or underscore).

E-mail address*    \S+@\S+\.\S+ 
Check for an at (@) sign and dot (.) and allow nonwhitespace characters only. 

Password        \w+ 
Any sequence of one or more word characters (letter, space, or underscore). Specific-length password \w{4,10} A password that must be at least four characters long but no longer than ten characters.

Advanced password         [a-zA-Z]\w{3,9} 
As with the specific-length password, this regular expression will allow four to ten total characters. The twist is that the first character must fall in the range of a–z or A–Z (that is to say. it must start with a nonaccented ordinary letter).

Another advanced password        [a-zA-Z]\w*\d+\w* 
This password starts with a letter character, followed by zero or more word characters, one or more digits, and then zero or more word characters. In short, it forces a password to contain one or more numbers somewhere inside it. You could use a similar pattern to require two numbers or any other special character.

Limited-length field        \S{4,10} 
Like the password example, this allows four to ten characters, but it allows special characters (asterisks, ampersands, and so on).

U.S. Social Security number     \d{3}-\d{2}-\d{4} 
A sequence of three, two, then four digits, with each group separated by a dash. You could use a similar pattern when requiring a phone number.

Thursday, January 10, 2013

Allow spaces when validating email using regular expressions

I have used below regular expression to validate the email address in asp.net RegularExpressionValidator control.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>

It's validating the email address correctly but when a user enter a space at the beginning or at the end of the email address the validator fired as its a invalid email address.

Below regular expression will ignore the spaces at the end and the beginning of the email address.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1"
ValidationExpression="\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*">*</asp:RegularExpressionValidator>

Tuesday, January 8, 2013

Phone Number Validator Class

Below sample class validates phone number for counties USA, UK and Netherland. You can add the validations for other countries to the class.

public class PhoneValidator {

static IDictionary<string, Regex> countryRegex =
new Dictionary<string, Regex>() {
{ "USA", new Regex("^[2-9]\\d{2}-\\d{3}-\\d{4}quot;)},
{ "UK", new
Regex("(^1300\\d{6}$)|(^1800|1900|1902\\d{6}$)|(^0[2|3|7|8]{1}[0-
9]{8}$)|(^13\\d{4}$)|(^04\\d{2,3}\\d{6}$)")},
{ "Netherlands", new Regex("(^\\+[0-9]{2}|^\\+[0-
9]{2}\\(0\\)|^\\(\\+[0-9]{2}\\)\\(0\\)|^00[0-9]{2}|^0)([0-9]{9}$|[0-9\\-
\\s]{10}$)")},
};

public static bool IsValidNumber(string phoneNumber, string country) {
if (country != null && countryRegex.ContainsKey(country))
return countryRegex[country].IsMatch(phoneNumber);
else
return false;
}

public static IEnumerable<string> Countries {
get {
return countryRegex.Keys;
}
}
}

Using the class:

string ContactPhone="465 567 56";
string Country="USA";

if (!PhoneValidator.IsValidNumber(ContactPhone, Country))
{
  //Validation Message
}

Friday, December 14, 2012

Regular Expressions:Match Number Patterns in Sql Server

When working with sql server some times we might need to add custom check constraints for the tables. One scenario that i have gone through is checking the phone number format when inserting into the table. What i did was, i have added a check constraint to the table for the phone number column using regular expressions.

The number format pattern i need to match is (800) 555-1212

ALTER TABLE #temp
ADD CONSTRAINT Chk_Phone CHECK (Phone LIKE '([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]')

[0-9] - Match any digit.

You can write a select query as below

Select * from #temp 
where Phone LIKE '([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'