My Slider

Image Slider By Humayoun Kabir Lets Express our emotion with blog Email me at humayounk@ymail.com #htmlcaption

বুধবার, ৪ ডিসেম্বর, ২০১৩

Regular Expression Shorcut Tutorial

Today I am going to write a tutorial on Regular Expression which is needed in daily basis of our programming life. And some of friends will agree with me that it can make us a little bit of trouble. But nothing to worry my dear friends . Here is the shortcut which i used in my programming life. If you don't like it please don't mind on me because i am not  a good blogger !!

RegExp has exec and test method

string has match,replace,search,split method for regular expression


var re = /ab+c/;  // You can call this way to initialize regular expression pattern

var re = new RegExp("ab+c"); // more standard when you not know the pattern [This is construct way]

/a*/ matches aaaaaaaa o or more times

but /a\*/ matches only a*

/a\b/ matches a with boundary word.
^ matches beginning of  input like as /^a/ matches in "a teddy bear" but not "A in E"

/ (foo) (bar) \1 \2/  // matches and remember first two words these called capturing parenthesis

/ (?:foo){1,2}/  non capturing parenthesis but not foo in "foo foo" but o in "foo"

x(?=y) match only if x is followed by y this is called look ahead

/ Jack (?=Frost|Sprat) / matches only jack followed by Frost or Jack Sprat.

x(?!y) match only if x is not followed by y negated look ahead
example : /\d+(?!\.)/ that matches "141" but not "3.141"

x|y matches either x or y
example : /green|red/ matches either in "green apple" or "red apple"

{n} matches exactly n occurrence of the preceding character
example : /a{2}/ matches in "caandy" but not in "candy"

{n,m} matches at least n and at most m occurrence of the preceding character
example : /a{1,2}/ matches 1 for in "Candy" , 2 for in "Caandy" , 3 for "Caaandy" and also in "Caaaaaaaaandy" because its matches preceding 3a like aaa

[xyz] matches any of the characters in brackets , this is same as [x-z]
example : [abcd] matches the 'b' in "brisket" and the 'c' in "city". The patterns /[a-z.]+/ and /[\w.]+/ match the entire string "test.i.ng".

[^xyz]  it matches anything that is not enclosed in the brackets
example: [^a-c] matches r in "briefcase"

[\b] matches a backspaces

\b matches a word boundary example: /\bm/ matches the m in "moon" , but  /\boo/ does not matches oo in "moon" because oo is followed by n , /oon\b/ matches in "moon" because oon is the end of word boundary.

\d matches a digit character equivalent to [0-9]

\s matches a single white space character example: /\s\w*/ matches bar  in "foo bar".

\w matches a alpha numeric character including the underscore equivalent to [A-Za-z0-9_]


Example with JavaScript (how to implement)

var myReg = /a(m+)i/g;
var myArray = myReg.exec("programming");
 
// Or this way If you want to construct the regular expression from a string 

var myReg = new RegExp("a(m+)i", "g");
var myArray = myRe.exec("programming");