WHAT'S NEW?
Loading...

Regular Expression in VB.Net


How to use Regular Expression in VB.net? Regular Expression (Regex) is a pattern matching for string parsing for string parsing and replacement. The best example for this Regex is the pattern of email addresses, urls, etc., obviously, it provides powerful tool to avoid entering unacceptable data in our system.

Quantifiers
  
Quantifier matches several characters you need to use. The most important quantifiers are *?+, where in * matches any number of what’s before it, from zero to infinity, ? matches zero or one, and + matches one or more.


Here are some available special characters available for regex building.
.
The dot matches any single character.
\n
Matches a newline character (or CR+LF combination).
\t
Matches a tab (ASCII 9).
\d
Matches a digit [0-9].
\D
Matches a non-digit.
\w
Matches an alphanumberic character.
\W
Matches a non-alphanumberic character.
\s
Matches a whitespace character.
\S
Matches a non-whitespace character.
\
Use \ to escape special characters. For example, \. matches a dot, and \\ matches a backslash.
^
Match at the beginning of the input string.
$
Match at the end of the input string.

Character classes

You can group characters by putting them between square brackets. This way, any character in the class will match one character in the input.
[abc]
Match any of a, b, and c.
[a-z]
Match any character between a and z. (ASCII order)
[^abc]
A caret ^ at the beginning indicates "not". In this case, match anything other than a, b, or c.
[+*?.]
Most special characters have no meaning inside the square brackets. This expression matches any of +, *, ? or the dot.
Here are some sample uses.
Regex
Matches
Does not match
[^ab]
cdz
ab
^[1-9][0-9]*$
Any positive integer
Zero, negative or decimal numbers
[0-9]*[,.]?[0-9]+
.111.2100,000
12.
Grouping and alternatives
It's often necessary to group things together with parentheses ( and ).
Regex
Matches
Does not match
(ab)+
abababababab
aabb
(aa|bb)+
aabbaaaabbaaaa
abab
Notice the | operator. This is the Or operator that takes any of the alternatives.
Sample code in Visual Basic.Net Regular Expression that count words and characters.
 Dim quote As String = txtdata.Text
 Dim numWords As Integer = Regex.Matches(quote, "\w+").Count
 Dim numChars As Integer = Regex.Matches(quote, ".").Count

 lblnumchar.Text = (numChars)
 lblnumofwords.Text = (numWords)
The above code must place in textchanged event or double click the specified textbox. You may also create you own pattern, here we go.

0 comments:

Post a Comment