Thursday, June 28, 2012

Javascript Pattern Matching

Referred URL http://js-x.com/page/javascripts__example.html?id=274

RegExp is an object, but anything between 2 "/"'s is a literally created object.

For Example:
var pattern = /s$/
(This matches any string ending with the letter "s")
Alternativly:
var pattern = new RegExp("s$")


JavaScript 1.2 adoptted Perl 4's regular expressions.
\f Formfeed
\n Newline
\r Carriage return
\t Tab
\v Vertical Tab
\xxx ASCII character specified by octal numbers xxx
\xnn ASCII character specified by hex number nn
\cX Control char ^X
These follow the "\" to represent that actual char:
\/.* ?|()[]{}


/[abc]/ matches "a", "b", or "c"
/[^abc]/ matches any char that is not "a", "b", or "c"
/[a-z]/ matches any lowercase letter
/[a-zA-Z0-9]/ matches any alpha-numeric


\s is any white character
\S is any non-white character
\w is any alpha-numeric
\W is any non-alpha-numeric
. is any character except a newline(\n) - or - [^\n]
\d is any digit
\D is any non-digit
[\b] literal backspace


/\d{2,4}/ matches between 2 and 4 digits
/\w{3}\d?/ matches exactly 3 word characters and an optional digit
/\s java\s / match "java" with one or more spaces before and after
/[^"]*/ match zero or more non-quote characters


{n,m} match previous expression at least n times but no more than m
{n,} same but no max
{n} same but exactly n times
? zero or one occurance of previous expression = same as = {0,1,}
match 1 more more = same as = {1,}
* match zero or more = same as = {0,}


/ab|cd|ef/ matches either "ab", "cd", or "ef"
/\d{3}|[a-z]{4}/ matches 3 digits or 4 lowercase letters

No comments: