Regular Expression in JavaScript

來源:互聯網
上載者:User

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
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.