JavaScript Regular expression RegExp, matching string, regular specified character

Source: Internet
Author: User
Tags constructor

EXEC () retrieves the specified value in the string, returns a value that is found, and returns null if no match is found:
The main regexp pattern matching method is exec (), similar to the match method for the string object described in the previous article. It's just a regexp method that takes a string as a parameter, not a string method that takes a RegExp object as a parameter. This sentence is a bit like tongue twisters, no way, the words in the book, copied over to let everyone happy, ah. The EXEC () method retrieves a match in a string, returns null if no match is found, and returns an array if it finds a match. The
is like Method match () for an array returned by a non-global search. The element 0 of this array contains a string that matches the regular expression, all the remaining elements contain substrings that match the subexpression, and the property index contains the position of the character that matches the occurrence, and the property input refers to the retrieved string.

  code is as follows copy code
/*
I is 0   http://www.xiaoxiaozi.com/index.php
I is 1  http
I are 2  www.xiaoxiaozi.com
I is 3  Inde x.php
I is index  one
I is input  my home is http://www.xiaoxiaozi.com/index.php
*/
var str = ' My Home is http://www.xiaoxiaozi.com/index.php ';
var pattern =/(w+):///([w.] +)/(s*)/;
//var result = Str.match (pattern);
var result = pattern.exec (str);
for (i)
{
        document.write (' I is ' +i+ ' &nbsp;& nbsp; " +result[i]+ "<br/>");
}

Unlike the match () method, the array type returned by exec () is different, regardless of whether the regular expression contains global property G. Because when the global attribute G is included, the match () method returns a matching array, and the regexp that invokes the Exec () method has a Lastindex property that sets the object's Lastindex property to the character position immediately following the substring.
when the same RegExp object invokes exec () for the second time, it retrieves from the character indicated by the Lastindex property, and if Exec () finds no match, it will break the Lastindex property to 0, ( At any time you can set the Lastindex property to 0, and whenever you find the last match in a string, you start using the same RegExp object to retrieve another string, and the method should be done when you discard the original search. This particular behavior allows you to repeatedly invoke exec () to iterate through all the regular expression matches in a string.

  code is as follows copy code
/*
matched ' Java ' at position 0; Next search begins at 4
matched ' Java ' at p Osition 28; Next search begins the
*/
var pattern =/java/g
var text = "JavaScript are more fun than java!";
Var result;
while (result = pattern.exec (text)!= null)
{
        document.write ( "Matched '" + result[0] + "'" +
                 "at position" + Result.index +
           & nbsp;    "; Next search begins at "+ Pattern.lastindex + <br/>");
}test ()

Retrieves the specified value in the string, and the return value is True or false:
This method is much simpler, is also the most I usually use a method, its role is to check whether the string contains a regular expression of a match. Returns True if it is included, otherwise it returns false.
When a global regular expression invokes test (), its behavior is the same as the method exec (), that is, it retrieves a particular string from the location specified by lastindex, and if it finds a match, sets the lastindex to the position of the character immediately after the match. This way we can also use Method Test () to traverse the string, just as with the Exec () method.

The code is as follows Copy Code
/*
Next search begins at 4
Next search begins at 32
*/
var pattern =/java/g;
var text = "JavaScript is more fun than java!";
var result;
while (result = Pattern.test (text))
{
document.write ("Next search begins at" + Pattern.lastindex + "<br/>");
}

Summary and nagging:
The writing may be a bit dizzy, you may not be very understanding of lastindex, here again nonsense, string method Search (), replace () and match () are not like the regexp exec () and test () That uses the Lastindex property of the RegExp object (yes, this property is regexp the property of the regular Expression object), in fact, the string method simply resets the lastindex to 0. And you must remember that when you use EXEC () and test (), This lastindex property changes only when the matching flag is G global.


The string object supports four methods of using regular expressions, namely search (), replace (), match (), and split (). Let's explain each of these.

Search () retrieves the substring specified in the string, or retrieves a substring that matches the regular expression:
The search () method should be the simplest of these four methods. It returns the position of the starting character of the first matched substring, with the regular expression as a parameter, and returns 1 if there are no strings to match.

  code is as follows copy code
//return 11, The first character position of the string is 0
var str = ' Welcome to xiaoxiaozi.com ';
document.write (Str.search (/xiaoxiaozi/));
//Return-1, Because I did not specify the mode I
var str = ' Welcome to xiaoxiaozi.com ';
document.write (Str.search (/xiaoxiaozi/));
//Return 11, Because I specified the mode i
var str = ' Welcome to xiaoxiaozi.com ';
document.write (Str.search (/xiaoxiaozi/i));

The argument I passed in the example is a regular expression, and if the search () argument is not a regular expression, it will first be passed to the RegExp constructor and converted to a regular expression. But here's what you need to be aware of. Search () does not support global retrieval because it ignores the regular expression parameter flag G.
Replace () is used to replace some of the characters with some characters in a string, or to replace a substring that matches a regular expression:
Method replace () to perform a retrieval and substitution operation. Its first argument is a regular expression, and the second is the string to be replaced. It retrieves the string that invokes it, matching according to the specified pattern. If flag g is set in a regular expression, the method replaces all pattern-matching substrings in the retrieved string with a replacement string, otherwise it replaces only the first substring found that matches the pattern.
If the first argument for replace () is a string instead of a regular expression, the method retrieves the string directly, rather than converting it to a regular expression, as search (), using the RegExp () constructor.
//smoothly converted, output as:

The code is as follows Copy Code
Http://www.xiaoxiaozi.com say: "Welcome to Http://www.xiaoxiaozi.com.com"
var str = ' Xiaoxiaozi say: ' Welcome to xiaoxiaozi.com ';
document.write (Str.replace (/xiaoxiaozi/gi, ' http://www.xiaoxiaozi.com '));

We have described the "Grouping of regular Expressions", whose bracketed subexpression is numbered from left to right, and the regular expression remembers Guangxi, which matches each subexpression. If the symbol $ (I would say foreigners like US dollars) is added in the replacement string, replace () replaces the characters with Guangxi, which matches the specified subexpression.

  code is as follows copy code

//replace double quotes with ' , and the strings within the double quotes retain Xiaoxiaozi say: ' Welcome to xiaoxiaozi.com '
var str = ' Xiaoxiaozi say: ' Welcome to xiaoxiaozi.com ';
var pattern =/"([^"]*) "/; Matches a string in double quotes that contains no double quotes
document.write (str.replace (Pattern, "' '"));

//To Xiaoxiaozi marked red in xiaoxiaozi.com
var str = ' Xiaoxiaozi say: Welcome to xiaoxiaozi.com ';
var pattern =/(Xiaoxi Aozi). com/i;
document.write (str.replace (Pattern, "<font color= ' Red ' >$1</font>"));

In the example we just gave, the second argument to replace () is a string, in fact, the second parameter can also be a function, which can dynamically compute the replacement string, and its function is in the following order: matching the whole regular string, matching pattern 1 string, matching pattern 2 string ....
Capitalize the first letter of a string

The code is as follows Copy Code

Name = ' AAA bbb CCC ';

Uw=name.replace (/bw+b/g, function (word) {
Return word.substring (0,1). toUpperCase () +word.substring (1);}
);

document.write (UW);

Match () retrieves the specified value within the string, or finds a match for one or more regular expressions:
The match () method is the most commonly used string method whose only argument is a regular expression (or passing its arguments to the constructor regexp () to convert to a regular expression), and returns an array that contains the matching result. If the regular expression has a flag G, the array returned by the method contains all the matches that appear in the string.

The code is as follows Copy Code
result=["1", "2", "3", "4"]
var str = ' 1a 2b 3c 4d ';
var pattern =/d+/g;
var result = Str.match (pattern);
For (I, result)
{
document.write (Result[i]);
}

If the G flag is not set in the match () parameter, it does not have a global retrieval, but it still returns an array. In this case, the first element of the array is the matching string, and the remaining elements are the celestial expressions that are enclosed in parentheses. The array returned by Result,result[0] holds a complete match, and Result[1] holds the matching content, consistent with the second function parameter of replace ().

  code is as follows copy code
/*
I is 0   http://www.xiaoxiaozi.com/index.php
I is 1  http
I are 2  www.xiaoxiaozi.com
I is 3  Inde x.php
I is index  one
I is input  my home is http://www.xiaoxiaozi.com/index.php
*/
var str = ' My Home is http://www.xiaoxiaozi.com/index.php ';
var pattern =/(w+):///([w.] +)/(s*)/;
var result = Str.match (pattern);
for (i)
{
        document.write (' I is ' +i+ ' &nbsp;& nbsp; " +result[i]+ "<br/>");
}

In this case, we can see that if it acts on a non-global regular expression, the array returned by match also includes two other attribute--index and input, which contains the position of the character at the beginning of the string, and a copy of the target string.
Split () is used to split a string into an array of strings:
The last method of a string object about a regular expression is split (), which separates the string that calls it into a substring array by using a delimiter. The delimiter can be a character, a string, or a regular expression.

The code is as follows Copy Code
/*
Separate strings with a space
My
Home
Page
Is
Http://www.xiaoxiaozi.com
*/
var str = ' My home page is http://www.xiaoxiaozi.com ';
var result = Str.split ("");
For (I, result)
{
document.write (Result[i] + "<br/>");
}

The example above does not use regular expressions, but what if I have more than one grid in my string? And the results of this method is not accurate Ah, okay, I do not have a regular expression of it? s matches any Unicode spaces, what are we afraid of?

The code is as follows Copy Code
/*
Use regular expressions to s+ one or more spaces to separate strings
My
Home
Page
Is
Http://www.xiaoxiaozi.com
*/
var str = ' My home page is http://www.xiaoxiaozi.com ';
var result = Str.split (/s+/);
For (I, result)
{
document.write (Result[i] + "<br/>");
}

Nagging and summarizing:
Yes, this one's been written a long time, but it's almost finished, huh. The previous regular expression is equivalent to fishing tools, today's two articles (a later one) talk about fishing methods, only the appropriate way to combine practical tools to catch fish


The regular expression specifies the location of the match


Some special sequences in the regular expression match not the actual characters, but some of the special character positions in the string. I'll continue to list the characters in the table below that specify the matching locations, and give an example of each.

Anchor character for regular expression:
Character meaning
^ matches the beginning of a string, in multiple-row retrieval, matching the beginning of a line
$ matches the end of a string, in multiple-row retrieval, matching the end of a line
b matches the bounds of a word. In short, the position between the character W and W, or the position between the character W and the beginning or end of the string (note: [B] matches the backspace)
B matching characters with non-word boundaries
(? =p) forward declaration, which requires that the next character match the pattern p, but does not include those characters in the match
(?! P) Reverse forward declaration, requiring that the next character not match the pattern p
Example Description:
1. ^ Match the beginning of a string
This should be well understood, like saying I'm going to get a string that matches "Simaopig", and this string has to be in the front, where "Simaopig" is equivalent to the rules I've specified we can check it with the following code

The code is as follows Copy Code
var patt1=new RegExp ("^simaopig");


Matches the matching rule, requiring that the matched content be at the beginning of the string, so enter true here

The code is as follows Copy Code
document.write (Patt1.test ("Simaopig is the nickname of Keoko"));
document.write ("n");


Does not match the matching rule and is not "Simaopig" at the beginning of the string, so output false here

The code is as follows Copy Code
document.write (Patt1.test ("Keoko nickname is: Simaopig"));

2. $ matches the end of the string, which is similar to the previous ^, skipping over
3. b matches the border of a word
This should also be very understandable, for example, I want to match something must be a separate individual, for example, I want to match the "Simaopig", but "a Simaopig" will match, because the "Simaopig" here is a separate individual, independent words, and "Simaopiga" is not independent, as part of other strings

The code is as follows Copy Code
var patt1=new RegExp ("\bsimaopig\b");
var patt1 =/bsimaopigb/;
Simaopig is a separate word, so its output is true
document.write (Patt1.test ("Simaopig"));
document.write ("n");
Simaopig is not a separate word, so its output is false
document.write (Patt1.test ("Asimaopig"));

4. b matches the position that a word is not a boundary, which can be understood to be contrary to B, without much explanation.
5.? = with?! You can understand this as an operation: the first, you need to have a rule inside, such as you are Chengguan, you want to sell things inside must have cucumber, but in fact you do not need cucumber, but you ask it must sell cucumbers, because this is the above "turtle" set
The second thing you need is such a rule that you ask the vendor not to sell Persimmon, because Persimmon is what you want to sell, but actually what you want is still the other variety that the Hawker sells.

The code is as follows Copy Code
The requirement string must be simaopig to begin with, and must be followed by:, but what I really match is Simaopig
var patt1=new RegExp ("^simaopig (? =\:)");
Output true
document.write (Patt1.test ("Simaopig:is a true man, it ' s true"));
document.write ("n");
Output false
document.write (Patt1.test ("Simaopig welcome come to xiaoxiaozi.com it's Wrong"));

Summary and nagging:
This is the way it is, use the time to flip it, because I feel that I can not back down, but I gave a specific example, because the example is more than the boring definition easier to understand

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.