String string matches JavaScript regular expression _ regular expression

Source: Internet
Author: User

Using regular expressions for pattern matching in JavaScript code often uses some of the methods of string objects and RegExp objects, such as replace, match, search, and so on, as described below as a summary of the use of related methods, as required by the friend reference.

There are 4 ways to support regular expressions in a String object, respectively: Search, replace, match, split

Str.search (RegExp)

Definition: The search () method retrieves strings that match the expression RegExp in string str and returns the position of the first character of the first matching string. Returns-1 if no matching string is found.

For example:

var str = "Javascript";
Str.search (/script/); Returns the position of S in script to 4
str.search (/j/i);//Set regular expression is identity I: ignore case, Match to J, return position 0

However, the search () method does not support global search because the identity g of the regular expression parameter is ignored and the RegExp lastindex property is always retrieved from the beginning of the string, so it always returns the first matching 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 retrieve S 
str.replace (regexp, replacement)

Definition: The Replace () method is an operation that performs a find and replace. It matches the regular expression regexp to the string, then replaces it with a replacement, and if there is a global identity G, replaces all of the matching strings, otherwise only the first matching string is replaced.

The Replace method should be a more commonly used method, which is useful in string substitution operations. For example:

1, simple replacement

var str = "JavaScript";
Str.replace (/javascript/, ' JavaScript '); To replace string JavaScript with JavaScript

2, Global replacement

Global substitution of
var str = "JavaScript" using global representation G;
Str.replace (/a/g, ' B '); Replace all letters A with the letter B, and return to Jbvbscript

3, the use of special characters in replacement replacement, in the replacement $ characters have special meaning, specify the following table:

Take a look at the example:

1, with the child expression replacement: $, $
var str = "JavaScript";
Str.replace (/(Java) (script)/, ' $2$1 '); 
The expression () is a subexpression that corresponds to the contents of the first expression, that is, the java,$2 is script, so the result of the substitution is: Scriptjava 
//2, $& for positive-expression-matching string
var str = " JavaScript ";
Str.replace (/java/, ' $&-'); 
The regular expression is matched by direct Java, the result is Java, the value of $& is Java, and then the matching string is replaced with the strings $&-, and the result is java-script
//3, $ ' $ ' $$
var str = ' JavaScript ";
Str.replace (/ava/, "$ '"); $ ' to match the left text of Ava, then J, then the result of Ava after replacement is: Jjscript
str.replace (/ava/, "$");//$ ' to match the substring of Ava's right text, then script, The result of the substitution of Ava is: Jscriptscript
str.replace (/ava/, "$$");//$$ is the direct measure symbol, that is, insert a $ symbol, and replace the result: J$script

4, using replacement as a function to replace

The parameter replacement of replace can be a function rather than a string, and each match will call the function, and the string returned will be used as the replacement text. The first parameter of the function is a string of the entire matching pattern, followed by a string that matches the subexpression in the pattern, and can have 0 or more parameters. The next argument is an integer that declares where the match appears in Str. The final parameter is STR itself.

Take a look at an example:

Match matches the entire string, that is: ' abc12345#$*% '
//P1 is the first subexpression, ([^\d]*), matching 0 or more non-numeric characters, namely: ABC
//P2 as the second subexpression, (\d*), Matches 0 or more digits, namely: 12345
//P3 is the third subexpression, ([^\w]*), matching 0 or any non word characters. Equivalent to ' [^a-za-z0-9_] ', that is, #$*%
//offset is the location where the pattern match appears, the first character has been matched successfully, the position is 0
//string itself, that is, the abc12345#$*%
function Replacer (Match, p1, p2, p3, offset, string) {return
[P1, P2, P3].join ('-');
}
var newstring = ' abc12345#$*% '. Replace (/([^\d]*) (\d*) ([^\w]*)/, replacer); 
The result of the replacement is: abc-12345-#$*%

Str.match (RegExp)

Definition: the match () method is the most commonly used string regular expression method. Its only argument is a regular expression or a regexp () constructor to create a regular expression, and the return value is an array that contains the matching result.

The regexp regular expressions in the match () method are generally divided into two situations: there is a set global flag G and no global flag is set

1, have set the global flag

If global flag G 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); Matches all numbers that appear in the string and returns an array: [1,2,3]

2, no global flag set

If the global flag is not set, then it is not global and retrieves only the first match. In this case, the match () method matches the result also returns an array, the first element of the array is the matched string, and the remaining element is the subexpression in parentheses in the regular expression. Take a look at an example:

Non-global matching
var str = "Visit my blog at http://www.example.com";
Str.match (/(\w+): \/\/([\w.] +)/); return result: ["http://www.example.com", "http", "www.example.com"]
//Regular expression match results are: http://www.example.com
// The first subexpression (\w+) matches the result: an HTTP
//Second subexpression ([\w.]) Match Result: www.example.com

Str.split (delimiter, limit)

Definition: The split () method breaks down the string that calls it into an array of strings, and the delimiter used is its argument.

Parameters:

Delimiter: string or regular expression that splits the string from the place specified by the parameter.

Limit: Specifies the maximum length of the returned array, and if this argument is not set, the entire string will be split.

For example:

1, only pass one parameter, the default split whole string
var str = "A,b,c,d,e";
Str.split (', '); Returns a segmented array of strings: ["A", "B", "C", "D", "E"]
//2, incoming two arguments
var str = "A,b,c,d,e";
Str.split (', ', 3); Specify a qualified length, return the corresponding array: ["A", "B", "C"]
//3, use regular expression matching, no split string
var str = "AA44BB55CC66DD";
Str.split (/\d+/); By matching the number to split the string, but does not contain the split string, the result returned is: ["AA", "BB", "CC", "DD"];
4, the use of regular expression matching, including the split string
var str = "AA44BB55CC66DD";
Str.split (/(\d+)/); By matching the number to split the string, and the split string is included in the subexpression, the returned result is: ["AA", "" "," BB "," "", "CC", "" "," DD "]

About regular expression pattern matching string method of knowledge, small series for everyone to introduce here.

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.