Regular Expressions Meta Characters Usage with Examples






2.90/5 (7 votes)
Apr 26, 2006
2 min read

44996
Regular Expressions Usage with Examples
Introduction
Regular Expressions are one of those that programmers frequently fumble with. Regular Expression patterns can be used either to manipulate the string
s or for validations. So here are some of the expressions that would come in handy.
Regular Expressions are extensively used in UNIX shell programming using grep, sed compilers. A Regular Expression will have a set of literals and the following meta-characters.
Meta-Characters in Regular Expressions
.
Matches any single character
[ ]
Matches a single character contained in the brackets
Examples
[anil]
matches character ‘a’ or ‘n’ or ‘i’ or ‘l’[a-z]
matches any lowercase alphabet between a to z[Q-Z]
matches any uppercase alphabet between Q to Z[0-9]
matches any digit between 0 to 9
To match the meta-characters [
or ]
it needs to be inside the enclosing brackets.
[[]a-zA-Z]
, matches any upper or lower case alphabet along with square brackets.
Hyphen ‘-
’ can be matched if it is at the end or beginning of the square brackets.
[-a-z]
matches any alphabet between a to z or ‘-‘[acf-i-]
matches characters ‘a’ or ‘c’ or ‘f’ or ‘g’ or ‘h’ or ‘i' or ‘-‘
[^]
Matches a single character that is not in the brackets.
Example
[^anil]
matches any character other than ‘a’ or ‘n’ or ‘i’ or ‘l’.
^
Matches the beginning of the test string
.
$
Matches the end of the string
.
*
Matches 0
or more copies of the predecessor, which could be a character or a sub expression like [a-p]
.
Examples
[a-p]*
matches “” or “a
” or “abc
” or “p
” etc.A*
matches “” or “A
” or “AA
” or “AAA
” etc.
+
Matches 1 or more copies of the predecessor, which could be a character or a sub expression like [a-p]
.
Examples
[a-p]+
matches “a
” or “abc
” or “p
” etc.A+
matches “A
” or “AA
” or “AAA
” etc.
Expressions to Manipulate/Process Strings
Regex.Replace(“HowYouDoing”, "[A-Z]+", " $&");
Inserts space in front of each upper case letter in the string
.
Result would be “How You Doing
”.
Expressions to Validate Strings
Regex regex = new Regex(“[^0-9]”);
ReturnValue = Regex.IsMatch(<TestString>);
ReturnValue
will have true
if the <TestString>
is not a natural number, otherwise false
. Helps if you want to identify whether the <TestString>
is a decimal or a character string
.
Regex regex = new Regex(“^[0-9]*$”);
ReturnValue = Regex.IsMatch(<TestString>);
ReturnValue
will have true
if the <TestString>
is a positive natural number, otherwise false
.
Regex regex = new Regex(“^-[0-9]+$|^\+?[0-9]+$”);
ReturnValue = Regex.IsMatch(<TestString>);
ReturnValue
will have true
if the <TestString>
is a positive natural number, otherwise false
.
History
- 26th April, 2006: Initial post