Posts Tagged ‘asp.net validation regex’

Remove extra spaces from string using regular expression, asp.net, c#

Thursday, October 9th, 2008

 Removes extra space from the string using Regular expression.
public string RemoveExtaSpaces(string text)
{
Regex regex = new Regex(@”\s{2,}”, Options);
text = regex.Replace(text.Trim(), ” “); //This line removes extra spaces and make space exactly one.
//To remove the  space between the end of a word and a punctuation mark used in the text we will
//be using following line of code

regex=new Regex(@”\s(\!|\.|\?|\;|\,|\:)”); // “\s” whill check for space near all puntuation marks in side ( \!|\.|\?|\;|\,|\:)”); )
text = regex.Replace(text, “$1″);
return text;

}

Above function removes all extra spaces in the string to make one space exactly. Feel free to use, its been used and tested

Reqular experssion RegEx, C# , asp.net , vb.net

Friday, April 25th, 2008

Regular expression:

Regular Expression is a great way to manipulate strings for example matching, finding, validating Data, Specailly string manipulaion becames handy while we use reqular expression.

We can use Regular expression on both Serer and client side. We do use it with asp.net validation controls.

Charcther matching:

. ^ $ * + ? { [ ] \ | ( )

\d Matches any decimal digit. This is equivalent to the class [0-9].

\D Matches any non-digit character. This is equivalent to the class

[^0-9].

\s Matches any whitespace character; this is equivalent to the class

[ \t\n\r\f\v].

\S Matches any non-whitespace character; this is equivalent to the class [^ \t\n\r\f\v].

\w Matches any alphanumeric character; this is equivalent to the class [a-zA-Z0-9_].

\W Matches any non-alphanumeric character; this is equivalent to the class [^a-zA-Z0-9_].

Period or dot “.” When used in Reqular expression could be any charcter other than new line characters.

[1234]Cricket will return 1,2,3 or 4 if they occur before Cricket OR

[1-4]Cricket

[a-m] ranges between a-m and A-M

“\” backslash and “?” Question Mark

(?) is used to find occurrence of previous character

(\) is use dto find exact occurance of pervious character

4{3}Cricket will return 444Cricket

“^” carrot ^cricket if cricket are first 7 charcters

“$” dollar $crikct if cricket are 7 last charcters

“\w+” is a word occurrence

(*) estrick means all

To check decimal or dot use \.?

?# is used to write commetns inside regular expression

To remove html Tags use “< (.+?)>”

If Input is a valid number or not:

To check if an input provided is a valid number use following reuglar expression

“(^([0-9]*|\d*\d{1}?\d*)$)”

Understating above expression will help how it works.