Вы находитесь на странице: 1из 14

Module 2

Javascript

Pattern
matching

Pattern matching

JavaScript has two


approaches to pattern
matching operations

based on the RegExp


object
based on methods of the
String object

CHARACTER AND CHARACTER-CLASS


PATTERNS

Metacharacters are
characters that have
special meanings in some
contexts in patterns.
The following are the
pattern metacharacters:
\|()[]{}^$*+?.

Metacharacters can
themselves be matched
by being immediately
preceded by a backslash.
A period matches any
character except newline.

/snow./ matches snowy, snowe,


and snowd
/3\.4/ matches 3.4. but /3.4/ would
match 3.4 and 374, among others.
[abc] matches a , b & c
[a-h] matches any lowercase letter
from a to h
[^aeiou] matches any lowercase
letter except a, e, i, o & u

Preferred Character
Classes

ANCHORS

A pattern is tied to a string position with an


anchor.
A pattern can be specified to match only at the
beginning of the string by preceding it with a
circumflex (^) anchor.
For example, the /^pearl/ pattern matches
pearls are pretty but does not match My
pearls are pretty:
A pattern can be specified to match at the end of
a string only by following the pattern with a
dollar sign anchor.
For example, the /gold$/ pattern matches I like
gold but does not match golden:

PATTERN MODIFIERS

The modifiers are specified as letters just


after the right delimiter of the pattern.
The i modifier makes the letters in the
pattern match either uppercase or
lowercase letters in the string.
For example, the pattern /Apple/i matches
APPLE, apple, APPle, and any other
combination of uppercase and lowercase
spellings of the word apple.
The x modifier allows white space to
appear in the pattern.

Based on methods of the String


object

search(pattern)
replace(pattern,string)
match(pattern)
split(parameter)

search(pattern)

Returns the position in the


object string of the pattern
(position is relative to zero);
returns -1 if it fails
var str = "Gluckenheimer";
var pos = str.search(/n/);
/* position is now 6 */

replace (pattern, string)

Finds a substring that matches the


pattern and replaces it with the
string

(g modifier can be used)

var str = "Some rabbits are rabid";

str.replace(/rab/g, "tim");

str is now "Some timbits are timid"

$1 and $2 are both set to "rab"

match(pattern)

The most general pattern-matching


method

Returns an array of results of the


pattern-matching operation

With the g modifier, it returns an


array of the substrings that
matched

Without the g modifier, first


element of the returned array has

match(pattern)

var str = "My 3 kings


beat your 2 aces";

var matches =
str.match(/[ab]/g);

matches is set to ["b", "a",


"a"]

split(parameter)

The parameter could be a string


or a pattern

In either case, it is used to split


the string into substrings and
returns an array of them

"," and /,/ both work

Вам также может понравиться