JS Regular Expression

Source: Internet
Author: User
Tags character classes processing instruction

From: http://www.wxwdesign.cn/article/skills/javascript_regular_expression.htm

Regular Expressions are developed based on UNIX management tools such as grep and Ed. using regular expressions can make string processing more convenient. The following describes some basic knowledge about Javascript Regular Expressions:

1. Implementation of JavaScript Regular Expressions

Javascript supports regular expressions through the Regexp class in ecmascript. The Regexp object constructor can contain one or two parameters. The first parameter specifies the pattern string to be matched, and the second parameter specifies an additional processing instruction.

ExampleCode: Program code var Re = new Regexp ("test", "Gi ");

Method 2:Use Perl-style syntax (more common)

Program code var Re =/test/GI; // This method has the same effect as above

2. Method of Using Regexp object

The main Regexp object methods are: Regexp. Test (string) regexp.exe C (string) string. Match (Regexp) string. Search (Regexp)

2.1 test () method

Test () method. If the given string matches this pattern, true is returned; otherwise, false is returned.

Sample Code: program code var Re =/test /;
Alert (Re. Test ("this is the test content "));// Output "true"

2.2 exec () method

The Exec () method is similar to the test () method. However, exec returns an array with only one entry, which is the first match.

Sample Code: program code var Re =/test/GI;
Alert(re.exe C ("this is the test content "));// Output "test"

2.3 match () method

The match () method also returns an array, but the usage method is different from the above. The usage of match is string. Match (Regexp ).

Sample Code: program code var Re =/TE/GI;
Alert ("this is the test content"). Match (re ));// Output "te, te"

2.4 search () method

The search () method is similar to the string's indexof () method, and returns a matched position in the string.

Sample Code: program code var Re =/TE/I;
Alert ("this is the test content"). Search (re ));// OUTPUT 12

3. Use a regular expression in the string method

Use a regular expression in string. Replace () and string. Split.

3.1 string. Replace ()

Sample Code: program code var Re =/TE/GI;
Alert ("this is the test content"). Replace (Re, "OK "));// Output "this is the okst conoknt"

3.2 string. Split ()

Sample Code: program code var Re =/TE/GI;
Alert ("this is the test content"). Split (re ));// Output "this is the, St con, NT"

4. Use metacharacters

Javascript Regular Expression metacharacters: program code ([{\^$ | )? * +.

To use metacharacters in regular expressions at any time, they must be escaped.

Sample Code: program code var Re = /\? /// Match?
VaR re2 = new Regexp ("\\? ");// Match?

The second line uses two backslashes, mainly because the javascript string parser translates \?, To ensure that this problem does not occur, we need to use two backslashes before the metacharacters, which we call double escape.

5. Use special characters

In an expression, you can use the character string, or its ASCII code or Unicode code. To use the ASCII code to represent a character, you must create a two-digit hexadecimal code, add \ X to the front. For example, if the ASCII code of character B is 98 and the hexadecimal value is 62, It is \ x62.

Sample Code: program code var Re =/\ x62 /;
Alert (Re. Test ("blue "));// Output "true"

You can also use octal instead of hexadecimal representation.

Sample Code: program code var Re =/\ 142 /;// Use octal Representation
Alert (Re. Test ("blue "));// Output "true"

If Unicode is used to represent characters, a four-digit hexadecimal representation of the string is required. For example, the expression of B is \ u0062.

Sample Code: program code var Re =/\ u0062 /;// Unicode Representation
Alert (Re. Test ("blue "));// Output "true"

Other characters that require double escape: program code \ t \ n \ r \ A \ e \ CX \ B \ v \ 0

6. Regular Expression character classes

6.1 simple class [ABC...]

Sample Code: program code var Re =/[GTS] O/g;// Match go to so
Alert ("You go to bed, so will I"). Match (re ));// Output "go to so"

6.2 negative class [^ ABC]

The negative type mainly uses exclusion policies, such as [^ ABC], which is used to exclude three characters, a B and C.

Sample Code: program code var Re =/[^ GTS] O/g;// Exclude g t s + O
Alert ("You go to bed, so do I"). Match (re ));// Output "yo do"

6.3 range class [A-Z]

The range class is mainly a series of consecutive characters or numbers that are not convenient for enumeration.

Sample Code: program code var Re =/A [3-5]/g;
Alert ("A1, A2, A3, A4, A5, A6"). Match (re ));// Output "A3, A4, A5"

6.4 combination classes [a-z0-9 \ r \ n]

A combination class is a string composed of several methods.

Sample Code: program code var Re =/[a-b3-5]/g;
Alert ("A1, A2, A3, A4, A5, A6"). Match (re ));// Output "a, 3, A, 4, A, 5,"

6.5 pre-defined class

Common pre-defined classes: program code. [^ \ n \ r]
\ D [0-9]
\ D [^ 0-9]
\ S [\ t \ n \ x0b \ f \ r]
\ S [^ \ t \ n \ x0b \ f \ r]
\ W [a-zA-Z0-9]
\ W [a-zA-Z0-9]

7. quantifiers

7.1 simple quantifiersProgram code? {0, 1}
* {0 ,}
+ {1 ,}
{N} must appear n times
{N, m} appears at least N times, but not more than m times
{N,} appears at least N times

Sample Code: program code var Re =/g? OO? D? /G;// Matches the o go goo good oo Ood OD
Alert ("to go is good"). Match (re ));// Output "o go good"

7.2 greedy (? * + {N} {n, m} {n ,})

Greedy, first check whether the entire string matches. If no match exists, remove the last character and then perform the matching again. In this case, proceed with this rule ......

Sample Code: program code var STR = "abc abcd abcde ";
VaR Re =/. * C/g;// Greedy match
Alert(re.exe C (STR ));// Output "abc abcd abc"

7.3 lazy (?? *? +? {N }? {N, m }? {N ,}?)

The lazy matches the greedy match in the opposite direction. The Lazy matches the first character first. If it fails, it reads the next character to continue matching. This rule goes on...

Sample Code: program code var STR = "abc abcd abcde ";
VaR Re = /.*? C/g;// Greedy match
Alert(re.exe C (STR ));// Output "ABC"

7.4 dominant (? + * ++ {N} + {n, m} + {n,} +)

The attacker only attempts to match the entire string. If the entire string does not match, the browser does not support this method well and is not recommended.

8. Complex Mode

8.1 groups

Grouping is used by enclose a series of characters, character classes, and quantifiers with a series of parentheses.

Sample Code: program code var Re =/g (o) + GLE/g;"O" appears at least once
Alert ("gogle Google gooooogle"). Match (re ));// Output "gogle Google gooooogle"

8.2 backreference)

After grouping is used for regular matching, each group is stored in a special place. The special values stored in the group are called backreference ).

Sample Code: program code var Re =/(\ D + )/;
Re. Test ("123456789 ");
Alert (Regexp. $1 );// Output "123456789"

8.3 candidates

A candidate is an or choice. Separated by |.

Sample Code: program code var Re =/You | Me/g;
Alert ("Say you say me"). Match (re ));// Output "You, Me"

8.4 non-capturing group (? :)

Non-capturing groups are called non-capturing groups. Using Non-capturing groups can remove the time consumption of capturing group storage groups and improveProgramExecution efficiency.

Sample Code: program code var Re = /(? : \ D + )/;
Re. Test ("123456789 ");
Alert (Regexp. $1 );// Output ""

8.5 lookahead )(? =)

Sometimes you want a specific character to appear before another string to capture it. Forward view tells the regular expression generator to look forward to some characters without moving their positions. Forward Looking is negative (?!) And forward (? =.

Sample Code: program code var Re =/(good (? = LU)/g;
VaR STR = "Goodluck is Lucy ";
Alert (Str. Match (re ));// Output "good"

8.6 borderThe beginning of the Code ^ line
$ End of row
\ B word boundary
\ B Non-word boundary

Sample Code: program code var Re =/^ (. + ?) \ B/g;// Match words in a lazy way
VaR STR = "Goodluck is Lucy ";
Alert (Str. Match (re ));// Output "Goodluck"

8.7 multi-row mode (m)

Match multiple rows, often used with G.

Sample Code: program code var Re =/(\ W +) $/GM;// Match a word at the end of each line
VaR STR = "Goodluck is Lucy \ NGO to bed ";
Alert (Str. Match (re ));// Output "Lucy, bed"

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.