JavaScript之正则表达式(转载)

Regular Expression are very important in professional JavaScript.

There is a wonderful
resource
in Mozilla developer center.

Two ways to construct a regular expression

1. Literal expression

    re = /ab+c/g;
    

2. Constructor function

    re = new RegExp("ab+c", "g");
    

Possible Flags

1. g - global search.

2. i - case-insensitive search.

3. m - multi-line search.

Simple and Special characters

A regular expression is composed of simple characters (such as /abc123_/) and special
characters.

Some important special characters:

1. ^ - Matches beginning of input.

2. $ - Matches end of input.

3. * - Matches the preceding character 0 or more times.

4. + - Matches the preceding character 1 or more times.

5. ? - Matches the preceding character 0 or 1 time.

6. . - Matches any single character.

Sepcial character \

There are two meanings of the special charater.

1. Used before simple character, indicating that the next character is special.

    e.g. b is a simple character, \b is used to indicate a word
boundary.

    Some important special character with \:

    1. \b - Matches a word boundary.

    2. \d - Matches a digit character.

    3. \s - Matches a white space character, including space,
tab, line feed.

    4. \w - Matches any alphanumeric character including the
underscore. Equivalent to [A-Za-z0-9_].

JavaScript funtions to operate regular expression

1. exec - returns: array.

2. match - returns: array or null.

3. test - returns: true or false.

4. search - returns: index or -1.

5. replace - returns: string.

Examples:

    /d(b+)d/g.exec("cdbbdbsbz");    // ["dbbd", "bb"]
    "cdbbdbsbz".match(/d(b+)d/g);   // ["dbbd"]
    "cdbbdbsbz".search(/d(b+)d/g);  // 1
    /d(b+)d/g.test("cdbbdbsbz");    // true
转自: http://www.cnblogs.com/sanshi/archive/2009/06/26/1514067.html

转载于:https://www.cnblogs.com/johnwonder/archive/2010/03/02/1676843.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值