Javascript Regular Expression matches string

Source: Internet
Author: User
This article introduces the relevant information about the string matching by the javascript regular expression to the coders. For more information about coders, see. In JavaScript code, regular expressions are used for pattern matching. Some methods of String objects and RegExp objects are often used, such as replace, match, and search. The following is a summary of some methods.

The String object supports four regular expressions: search, replace, match, and split.

Str. search (regexp)

Definition: The search () method searches for strings matching the expression regexp in string str and returns the position of the first character of the first matching string. If no matching string is found,-1 is returned.

For example:

Var str = "Javascript"; str. search (/script/); // return the position of s in the script as 4str. search (/j/I); // set the regular expression to identify I: Ignore case sensitivity, match to J, return position 0

However, the search () method does not support global search, because the identification g of the regular expression parameter is ignored, and the lastIndex attribute of regexp is also ignored, which is always retrieved from the starting position of the string, so it will always return the first matched position of str.

For example:

Var str = "javascript is cool"; str. search (/s/g); // returns the s position 4 in javascript and does not continue to search for s

Str. replace (regexp, replacement)

Definition: The replace () method is used to perform the search and replace operation. It replaces the string matched by the regular expression regexp with the replacement string. If the global ID g exists, it replaces all matched strings. Otherwise, only the first matched string is replaced.

The replace method should be a commonly used method, which is very useful in string replacement operations. For example:

1. Simple replacement

Var str = "javascript"; str. replace (/javascript/, 'javascript '); // replace string JavaScript with javascript

2. Global replacement

// Use global representation g to replace var str = "javascript"; str. replace (/a/g, 'B'); // replace all letters a with B and return jbvbscript

3. Replace with special characters in replacement. The $ character in replacement has special meanings. The specific descriptions are as follows:

Character Replace text
$1, $2,..., $99 Text that matches the 1st to 99 subexpressions in regexp
$ & String Matching regexp
$' Text on the left of the matched substring
$' Text on the right of the matched substring
$ Direct Volume symbol

Let's take a look at the following example:

// 1. Replace with a subexpression: var str = "javascript"; str. replace (/(java) (script)/, '$2 $ 1'); // () in the expression is a subexpression. $1 corresponds to the content of the first expression, that is, java, $2 is the script, so the replacement result is: scriptjava // 2, $ & is the string matching the positive expression var str = "javascript"; str. replace (/java/, '$ &-'); // regular expressions are matched by directly adding java. If the matching result is java, the value of $ & is java, then replace the matched string with the string $ &-. The result is java-script // 3 and $ '$ var str = "javascript"; str. replace (/ava/, "$ '"); // $' indicates the left-side Text of the matched substring ava. If it is j, the result of the replaced ava is jjscriptstr. replace (/ava/, "$ '"); // $' indicates the text to the right of the matched substring ava. If it is script, the result of replacing ava is jscriptscriptstr. replace (/ava/, "$"); // $ is a direct volume symbol, that is, insert a $ symbol, with the result of j $ script

4. replacement is used as the function replacement.

The replacement parameter of replace can be a function rather than a string. This function is called for each matching. The string returned by replace is used as the replaced text. The first parameter of this function is the string of the entire matching mode. The following parameter is a string that matches the subexpression in the mode. There can be 0 or more parameters. The following parameter is an integer that declares the position where the matching occurs in str. The final parameter is str itself.

Let's look at an example:

// Match matches the entire string, that is, 'abc12345 # $ * % '// p1 is the first subexpression ([^ \ d] *), match 0 or more non-numeric characters, that is, abc // p2 is the second subexpression, (\ d *), matching 0 or more numbers, that is: 12345 // p3 is the third subexpression ([^ \ w] *). It matches 0 or any non-word characters. Equivalent to '[^ A-Za-z0-9 _]', that is, # $ * % // offset is the position where the pattern match appears, since the first character has been matched successfully, the position is 0 // string, that is, abc12345 # $ * % function replacer (match, p1, p2, p3, offset, string) {return [p1, p2, p3]. join ('-');} var newString = 'abc12345 # $ * % '. replace (/([^ \ d] *) (\ d *) ([^ \ w] *)/, replacer); // replace the result: abc-12345-# $ * %

Str. match (regexp)

Definition: the match () method is the most common String regular expression method. Its unique parameter is a regular expression or a RegExp () constructor to create a regular expression. The returned value is an array containing matching results.

The regexp Regular Expression in the match () method is generally divided into two situations: the global flag is set and the global flag is not set.

1. Set global flag

If the global flag is set, the returned array contains all the matching results that appear in the string. For example:

// Global match var str = "1 plus 2 equals 3"; str. match (// d/g); // match all numbers in the string and return an array: [, 3]

2. No global flag is set.

If the global flag is not set, it is not a global search, but the first match is retrieved. In this case, the match () method returns an array. The first element of the array is the matched string, the remaining elements are the child expressions enclosed in parentheses in the regular expression. Let's look at an example:

// Var str = "visit my blog at http://www.example.com"; str. match (/(\ w +): \/([\ w.] +)/); // return result: ["http://www.example.com", "http", "www.example.com"] // The result of regular expression matching is: http://www.example.com // match result with the first child expression (\ w +): http // second child expression ([\ w.]) matching result: www.example.com

Str. split (delimiter, limit)

Definition: The split () method can break down the string that calls it into a string array. The delimiter used is its parameter.

Parameters:

Delimiter: a string or regular expression that separates a string from the specified position.

Limit: specifies the maximum length of the returned array. If this parameter is not set, the entire string is split.

For example:

// 1. pass only one parameter. By default, the entire string var str = "a, B, c, d, e"; str. split (','); // returns the split string array: ["a", "B", "c", "d ", "e"] // 2. Input two parameters var str = "a, B, c, d, e"; str. split (',', 3); // specify the length limit, the corresponding array is returned: ["a", "B ", "c"] // 3. Use a regular expression to match the string, excluding the split string var str = "aa44bb55cc66dd"; str. split (/\ d +/); // the string is separated by matching digits, but the string is not included, the returned result is: ["aa", "bb ", "cc", "dd"]; // 4. Use a regular expression to match, including the split string var str = "aa44bb55cc66dd"; str. split (/(\ d +)/); // split the string by matching digits, and the string to be split is contained in the subexpression. The returned result is: ["aa", "44", "bb", "55", "cc", "66", "dd"]

For more information about the String method of regular expression pattern matching, I will introduce it here.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.