RegExp: A JavaScript RegExp object, regexpjavascript.

Source: Internet
Author: User

RegExp: A JavaScript RegExp object, regexpjavascript.

Overview

RegExp constructor creates a regular expression object that uses the pattern to match the text.

For more information about regular expressions, see the regular expressions section in the JavaScript guide.

Syntax

Text and constructor are possible:
/Pattern/flags new RegExp (pattern [, flags])

Parameters

Pattern
Regular Expression text
Flags
If specified, the flag can have any combination of the following values:

G
Global match
I
Case Insensitive
M
Multiple rows; let the start and end characters (^ and $) work in multi-row mode (for example, ^ and $ can match the start and end of each row in the string (the row is separated by \ n or \ r), not just the start and end of the entire input string.
U
Unicode. Use the mode as the sequence of Unicode code points.
Y
Viscosity; in the target string, match only from the display position specified by the lastIndex attribute of the regular expression (and do not try to match from any subsequent index ).
Description
There are two ways to create a regular object: literal and constructor. To represent a string, the literal form does not use quotation marks, but the parameters passed to the constructor use quotation marks. The following expression creates the same regular expression:

/ab+c/i;new RegExp('ab+c', 'i');new RegExp(/ab+c/, 'i');

When an expression is assigned a value, the compilation State of the regular expression is provided in the literal form. When the regular expression remains constant, the literal value is used. For example, when you construct a regular expression using a literal in a loop, the regular expression will not be re-compiled in each iteration (recompiled ).
The constructor of the regular expression object, such as new RegExp ('AB + C'), provides the runtime compilation function ). If you know that the regular expression mode will change, or you do not know the mode in advance, but get it from another source, such as user input, you can use constructors.
Starting from ECMAScript 6, when the first parameter is a regular expression and the second flag parameter exists, new RegExp (/AB + c/, 'I ') the TypeError ("flag not supported when constructing from other regular expressions") is no longer thrown. Instead, a new regular expression is created using these parameters.

When using constructors to create a regular object, regular character escape rules are required (add backslash \ In Front \). For example, the following is equivalent:

var re = new RegExp("\\w+");var re = /\w+/;

Define Regular Expressions literally
var expression = /pattern/ flags;
The pattern part can be any simple or complex Regular Expression representation.
Flage indicates the behavior of the regular expression 1.g: global mode. It does not stop 2. I: case-insensitive mode 3.m: multiline mode after the first match is found.
Example:

Var pattern1 =/at/g; // match all atvar pattern2 =/[bc] at/I in the string; // match the first "bat" or "cat ", case Insensitive var pattern3 = /. at/gi; // global match. at "end" of three characters. Case Insensitive

All metacharacters used in the mode must be escaped. The metacharacters in the regular expression include: [{^ $ |? * +.}])
Example:

Var pattern4 =/\ [bc \] at/I; // match the first "[bc] at", case insensitive

Use the RegExp constructor to accept two parameters: parameter 1: String mode to be matched, parameter 2: Optional flag Behavior
Example:

var pattern5 = new RegExp("[bc]at", "i");

Note: Because the Pattern Parameters of the RegExp constructor are strings, double escaping is required in some cases. Double escape is required for all metacharacters

Example:
Literal equivalent string
/\ [Bc \] at/"\ [bc \]"
/\. At/"\."
/Name/\ age/"name \/age"
/\ D. \ d {1, 2}/"\ d. \ d {1, 2 }"
/\ W \ hello \ 123/"\ w \\\ hello \\\ 123"

Note: Unlike the regular expression created by instantiating a RegExp, a literal will always share the same RegExp instance (ECMAScript3 ). Each new RegExp instance created using the constructor is a new instance.

RegExp instance attributes

Console. log (pattern5.global); // false whether the g flag console is set. log (pattern5.ignoreCase); // whether the I flag console is set to true. log (pattern5.multiline); // false whether the m flag console is set. log (pattern5.lastIndex); // start from 0 to search for the start position of the next matching item console. log (pattern5.source); // [bc] at regular expression String Representation

Inherited attributes

Console. log (pattern5.toString (); // [bc] at/I Regular Expression literally represents the console. log (pattern5.toLocaleString (); // [bc] at/I Regular Expression literally represents the console. log (pattern5.valueOf (); // [bc] at/I Regular Expression literal representation

RegExp instance method
Method 1: exec (), which accepts a parameter that applies both the mode string. Returns an array containing the first matching item information. If no matching item exists, null is returned. The returned array instance contains two attribute indexes (The position of the matching item in the character) and input (strings that apply regular expressions ).

var text = "huang jin liang shi ge hao ren";var pattern6 = new RegExp("huang( jin liAng( shi ge hao ren)?)?", "i");var matches = pattern6.exec(text);console.log(matches); //[ 'huang jin liang shi ge hao ren',// ' jin liang shi ge hao ren',// ' shi ge hao ren',// index: 0,// input: 'huang jin liang shi ge hao ren' ]var text1 = "cat, bat, sat";var pattern7 = new RegExp(".at")var matches1 = pattern7.exec(text1);console.log(matches1); //catvar pattern8 = new RegExp(".at", "gm");var matches2 = pattern8.exec(text1);console.log(matches2); //catvar matches3 = pattern8.exec(text1);console.log(matches3); //batvar matches4 = pattern8.exec(text1);console.log(matches4); //satvar matches5 = pattern8.exec(text1);console.log(matches5); //null

Method 2: test (), which accepts a parameter that applies both the mode string. If this mode matches this parameter, true is returned; otherwise, false is returned.

Var text2 = "000-00-0000 "; var patterexp = new RegExp ("\ d {3}-\ d {2}-\ d {4}"); console. log (pattern9.test (text2) console. log (text2); if (pattern9.test (text2) {console. log ("matched");} else {console. log ("matching failed ");}

Constructor attributes (not supported by some browsers)
Long attribute name short attribute Name Description
Input $ _ string to be matched last time
LastMatch $ & last match
LastParen $ + last capture group
LeftContext $ 'text before lastMatch in the input string
Multiline $ * Boolean, whether it is multiline Mode
RightContext $ 'text after lastMatch in the input string
$1 ~ $9 is used to store the capture groups

Limitations in ECMAScript
1. Match the \ A and \ Z anchors whose strings start and end
2. Search backward
3. Union set and intersection class
4. Atomic Group
5. Unicode support (except for a single character)
6. Name a capture group
7. s and x matching Modes
8. Condition matching
9. Regular Expression comments

I just found a method that matches multiple lines in a js.

<script>var s = "Please yes\nmake my day!";alert(s.match(/yes.*day/));// Returns nullalert(s.match(/yes[^]*day/));// Returns 'yes\nmake my day'</script>

Unfortunately, editplus is not available, and it is more convenient to use dw in many cases.

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.