Tuesday, April 24, 2007

Regular Expressions
the following codes in this article throws light to some of the commonly used regular expression..all are coded with c#,asp.net

How to Find a text and Replace with other text
string FindAndReplace(string text)
{
string str = text;
Regex rgx = new Regex( class="str">@"\bbuddha\b");
if (rgx.IsMatch(text))
{
str = rgx.Replace(str, "mybuddha");
}
return str;
}


Testing complexity of password using regular expression validator
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1"
ErrorMessage="RegularExpressionValidator" ValidationExpression="(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{7,15}"></asp:RegularExpressionValidator></div>


Splitting comma seperated files with a br tag
string SplitLine(string text)
{
string str = text;
Regex rgx = new Regex(@",\s*");
if (rgx.IsMatch(text))
{
str = rgx.Replace(str, ",<br>" );
}
return str;
}

SplitLine("Microsoft,Linux,Oracle");
will return
Microsoft,
Linux,
Oracle




Extracting Query Strings from URLs
Regex rgx= new Regex( "\\?(?<query>[^<>#\"]+)" );




Extracting Filenames from Paths
Regex rgx = new Regex( ?
"(?<path>(\\\\(?<file>[^\\\\/:*?\"<>|.][^\\\\/:*?\"<>|]*))+)" );




Extracting Extensions from Filenames
Regex rgx = new Regex( ?
"\\\\[^\\\\/:*?\"<>|]+\\.(?<ext>[^.\\\\/:*?\"<>|]+)" );




Formatting U.S. Dates
Regex rgx = new Regex( @"^(\d{1,2})[-\/.]?(\d{1,2})[-\/.]?((?:\d{2}|\d{4}))$" );




Formating Dates
string FormatDates(string text)
{
string str = text;
Regex rgx = new Regex(@"(?:(?<=^)|(?<=[^\d]))(\d)(?=[^\d])");

if (rgx.IsMatch(text))
{
str = rgx.Replace(str, @"0$1");
}

return str;

}
1/1/2007 will become 01/01/2007




Validating Credit Card Numbers
<asp:RegularExpressionValidator Id="revInput" RunAt="server"
ControlToValidate="txtInput"
ErrorMessage="Please enter a valid value"
ValidationExpression="^(\d{4}-){3}|(\d{4} ){3}\d{4}|\d{15,16}|?
\d{4} \d{2} \d{4} \d{5}|\d{4}-\d{2}-\d{4}-\d{5}$"
>
</asp:RegularExpressionValidator>




Validating Dates in MM/DD/YYYY Format
<asp:RegularExpressionValidator Id="revInput" RunAt="server"
ControlToValidate="txtInput"
ErrorMessage="Please enter a valid value"
ValidationExpression="^(0?2/(0?[1-9]|[12][0-9])|
(0?[469]|11)/(0?[1-9]|[12][0-9]|30)|
(0?[13578]|1[02])/(0?[1-9]|[12][0-9]|3[01]))/\d{4}$"
>
</asp:RegularExpressionValidator>



No comments: