Common JavaScript Regular expressions

Source: Internet
Author: User
Tags character classes regular expression string methods

1. The implementation of JavaScript regular expressions

JavaScript support for regular expressions is implemented through the RegExp class in ECMAScript, where the constructor of the RegExp object can take one or two parameters. The first parameter describes the pattern string that needs to be matched, and the second parameter specifies additional processing instructions.

Sample code:
Program code

var re=new RegExp ("Test", "GI");


How to implement two: Use Perl-style syntax (more commonly used)


Program code
var re=/test/gi; This way is the same as the above


2. Methods of using RegExp objects

The main methods of RegExp objects are: Regexp.test (String) regexp.exec (String) string.match (REGEXP) string.search (REGEXP)

2.1 Test () method

The test () method returns True if the given string matches this pattern, otherwise it returns false.

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 test (), but exec returns an array with only one entry, both the first match.

Sample code:
Program code

var re=/test/gi;
Alert (Re.exec ("This is the test content"); Output "Test"


2.3 Match () method

The match () method also returns an array, but the use method differs from the above, and match is used 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, like the IndexOf () method of the string, returns a matching position that appears in the string.

Sample code:
Program code

var re=/te/i;
Alert ("This is the test content"). Search (re); Output 12


3. Using regular expressions in string methods

Use regular expressions in String method 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. Using meta characters

JavaScript regular expression meta-character:

Program code
( [ { ^ $ | ) ? * + .

Any time you want to use metacharacters in regular expressions, you must escape them.

Sample code:
Program code

var re=/?///Match?
var re2=new RegExp ("\?"); The?

The second row uses two backslashes in its definition, mainly because the JavaScript string parser translates as n, and in order to ensure that this problem is not present, it is called Double escape to use two backslashes before the metacharacters.

5. Use special characters

You can use the string itself in an expression, or you can use its ASCII code or Unicode code to represent a character in ASCII code, you must make a two-bit hexadecimal code and precede with an X. For example, the ASCII code for character B is 98, converted to 16 to 62, both x62.

Sample code:
Program code

var re=/x62/;
Alert (Re.test ("Blue")); Output "true"


Alternatively, you can use octal instead of hexadecimal notation.

Sample code:

Program code

var re=/142/; Using octal representation
Alert (Re.test ("Blue")); Output "true"


If you use Unicode to represent a character, you must make a four-bit hexadecimal representation of the string, such as B in the form of: u0062

Sample code:

Program code

var re=/u0062/; Use Unicode representation
Alert (Re.test ("Blue")); Output "true"


Some other characters that require double escape:

Program code
T n r r A e CX B V

6. Regular expression character class

6.1 Simple class [ABC ...]

Sample code:
Program code

var re=/[gts]o/g; Match Go
Alert ("You go to Bed,so would I"). Match (re); Output "Go to"


6.2 Negative class [^ABC]

A negative class is primarily an exclusion policy, such as [^ABC], which excludes a B c three characters.

Sample code:
Program code

var re=/[^gts]o/g; Excluding G T s +o
Alert ("Go to Bed,so do I"). Match (re); Output "Yo do"


6.3 Range class [A-Z]

A range class is primarily an inconvenient enumeration, but a continuous series of characters or numbers.

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 class [A-Z0-9RN]

A composition class is a string that is grouped into several ways.

Sample code:

Program code

var re=/[a-b3-5]/g;
Alert (("A1,a2,a3,a4,a5,a6"). Match (re); Output "A,a,a,3,a,4,a,5,a"


6.5 Predefined classes

Common Predefined classes:
Program code

. [^NR]
d [0-9]
D [^0-9]
s [TNX0BFR]
S [^ tnx0bfr]
w [a-za-z0-9]
W [^a-za-z0-9]

7. quantifier

7.1 Simple quantifiers

Program 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; Can match o go goo good oo ood od
Alert (("to The Go Good"). Match (re); Output "O Go Good"


7.2 Greedy (? * + {n} {n,m} {n,})

Greedy first look at the entire string is matched, if there is no match, remove the last character, and then again to match, with this rule go on ...

Sample code:
Program code

var str= "abc abcd ABCDE";
var re=/.*c/g; Greedy Way to match
Alert (re.exec (str)); Output "ABC abcd ABC"


7.3 Lazy (?? *?  +?  {n}?  {n,m}? {n,}?)

Lazy and greedy to match the direction of the opposite, lazy first from the first character to match, if not successful, go to the next character to continue to match, with this rule go on ...


Sample code:
Program code

var str= "abc abcd ABCDE";
var re=/.*?c/g; Greedy Way to match
Alert (re.exec (str)); Output "ABC"


7.4 dominating (? + *+ + + {n}+ {n,m}+ {n,}+)

Only attempts to match the entire string, if the entire string does not match, do not make further attempts, this method browser support is not very good, not recommended.

8. Complex model

8.1 Grouping

Grouping is used by enclosing 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 1 times
Alert ("Gogle Google Gooooogle"). Match (re); Output "Gogle Google Gooooogle"


8.2 Reverse Reference (backreference)

After a regular match with a group, each packet is stored in a special place, which is stored in a special value in the packet, which we call a reverse reference (backreference).

Sample code:
Program code

var re=/(d+)/;
Re.test ("123456789");
alert (regexp.$1); Output "123456789"


8.3 Candidates

The candidate is actually an or choice. Use | separate.

Sample code:
Program code

var re=/you|me/g;
Alert ("Say You Say Me"). Match (re); Output "You, Me"


8.4 Non-capture groupings (?:)

Instead of creating groupings of reverse references, which we call non-capture groupings, you can eliminate the time consuming of captured packet storage groupings and improve program execution efficiency by using non-capture groupings.

Sample code:

Program code

var re=/(?:d +)/;
Re.test ("123456789");
alert (regexp.$1); Output ""


8.5 Forward (lookahead) (? =)

Sometimes, you want a particular character to appear in front of another string before it is captured.  Forward-looking tells the regular expression operator to look forward to some character without moving its position. Forward-looking has negative direction (?!) and positive (? =) points.

Sample code:
Program code

var re=/(Good (? =lu))/g;
var str= "Goodluck is Lucy";
Alert (Str.match (re)); Output "good"


8.6 borders

Program code

^ Line Start
$ line End
b The boundary of a word
B a 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-line mode (m)

Match multiple lines, often with G use.

Sample code:
Program code

var re=/(w+) $/gm; Match one word at the end of each line
var str= "Goodluck is Lucyngo to bed";
Alert (Str.match (re)); Output "Lucy, bed"

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.