JS Regular Expressions

Source: Internet
Author: User
Well, let's say a few times. Last year, C # was used to make a small syntactic highlight item. According to the information in the preparation file Code Format it into HTML so that it can display the same effect of syntax element highlighting as in the editor on the webpage and support code folding. Yes, it's similar to what we see in the blog. Because I was using MSN space, it didn't provide this function, so I had to write it myself.

I used C # for compiling. At first I used basic statements such as for, while, switch, and if to judge keywords, I was so stupid that I didn't know what the regular expression was, so I had to use this method. Of course, the method still worked, but it was a lengthy code in a function, I am afraid it will be very difficult to maintain it in the future. I thought that other software could not be written like this, so I searched Google for a while and found some code with syntax highlighting and open-source projects, start up and take a look ..... Dizzy: It's so complicated. To be honest, what I do not like most is to look at other people's code. It's not that I'm pretentious. It's really dizzy to look at other people's code, unless there is a very detailed description of the document, I don't want to look at it when I look at it. At most, I want to look at how other people's interfaces are written, and then I guess how they implement them internally.

Although the search results are not very helpful, I still learned about the regular expression and forgot where to see it. At that time, I began to study the regular expression while transforming my "broken things ". Then it wasn't long before I started a new blog in the blog garden. I finally opened the syntax highlight function in the blog garden. So I lost a major motivation when I wrote a code HTML highlight. Secondly, the C # syntax highlighting module can only run on the server side or winformProgramAnd I finally want to get HTML code to display on the page, I think it is best for the client script. Unfortunately, I don't know much about Js... Later, during this period of time, I made another mistake and did not improve the grammar brightening module any more.

I went back to work overtime last night and planned to continue learning the UML model. Later I remembered that the company had a module that needed to extract all the HTML tags in the returned results from the database, I opened regexbuddy, a regular expression tool. The results of regexbuddy help document saw the JScript using regular expressions of Simple teaching, so almost curious again, open the UltraEdit-32 began to write a simple JavaScript test.

During the experiment, I will not repeat the nonsense here, because many places are repeatedly trying to bypass a lot of detours. Here I will directly explain the usage of the regular expression in the JScript.

Now, let's get started!

The Prime Minister talked about Regexp, the regular expression object of JScript.

The class that provides regular expression operations in JScript is called Regexp. You can instantiate Regexp objects in two ways.

Method 1: constructor instantiation:

VaR myregex = new Regexp ("\ W +", "IgM ");
// \ W + is the actual regular expression. Note that the first \ is used for escaping. The IgM indicates case-insensitive, global search, and multi-row search, which will be explained later.
Method 2: Direct Value assignment:

VaR myregex =/\ W +/IgM;
// The effect is the same as that of the previous statement, but the transfer character is not required here. The original regular expression looks like what it looks like, and the IgM works the same as the previous example.
I personally think that regular expressions written in the second method are easier to read. The regexbuddy help document also recommends the second method. The Regexp object contains the following operations:

Exec (string Str): Execute Regular Expression matching and return matching results. According to the running result of the msdn example, every execution of exec starts from the end position of the previous direct match, in addition, the returned value seems to be an rerexp object, while regexbuddy returns an array but does not provide a detailed example. I think it is more reliable Based on the test results.

Compile (string RegEx, string flags): Pre-compiled regular expressions to run faster. After testing, the efficiency is significantly improved after pre-compilation. The RegEx parameter is a regular expression, and flags can be a combination of the following three values: G-global search, my test results show that only the first matching string can be matched without the G sign. I-ignore case-insensitive M-multi-row search. It seems that multi-row search is already performed by default.

Test (string Str): returns true if STR matches the regular expression; otherwise, returns false, which is similar to the match method of the string object.

The Regexp object contains the following attributes:

Index: the position of the First Matching expression in the string, initially-1
Input: match the target of the regular expression. Note that it is read-only.
Lastindex: the position of the next matching expression. The original statement is (returns the character position where the next match begins in a searched string.). I do not know whether there is a translation error. I have not used this attribute.
Lastmatch: string of the last matching expression
Lastparen: The last matched sub-match string. For example, a regular expression contains multiple matching items grouped by (). lastparen indicates the matching result of the last group.
Leftcontext: All characters starting from the start of the target string to the start position of last match.
Rightcontext: All characters from the end position of last match to the end position of the entire target string.
$1... $9: indicates the matching result of group N. This is useful when multiple groups in the regular expression are grouped ().

Next, let's talk about the operations related to the regular expression of the string object in JScript:

Match (string RegEx): accepts a regular expression and returns whether the string matches the regular expression.
Replace (srting RegEx, string Str): replace the substring that matches the regular expression with Str. This function seems simple, but it also hides more advanced usage. See the following example.
Example 1:

VaR str1 = "A: My name is Peter! \ NB: Hi Peter! ";
Str1 = str1.replace (/Peter/g, "Jack ");
Alert (str1 );
In this example, the string is replaced. The power of this expression is certainly not limited to this. If you are skilled, you can use it to do a lot of work that previously required a lot of code. For example, add the highlighted HTML tag before and after the code keyword. From the previous example, it seems that replace can only replace the matched text with the new text. How can we use it to insert tags before and after keywords? As you can imagine, if you can use the matching results when you replace them, you just need to replace the keyword with: Tag header + keyword + tag tail.

But how can we use regular expression matching results in replace?

In this case, we need to use the "matching variable". The matching variable is used to represent the result of regular expression matching. The following describes the matching variables:
$ & -- Indicates the matching results of all matching groups. The matching group is the () Group of the regular expression.
$ -- Represents $ characters. Because $ characters are used for matching variables, escape
$ N -- similar to the previous $1... $9 indicates the result of group N matching
$ NN -- the result of the NN group match is very simple.
$ '-- The leftcontext mentioned above. For example, if abcdefg is matched with D, ABC is its leftcontext.
$ '-- It is very close to the above and should not be mistaken !, This is rightcontext. EFG is the rightcontext in the above example. Now we need to insert tags before and after keywords:

VaR str1 = "A: My name is Peter! \ NB: Hi Peter! ";
Str1 = str1.replace (/Peter/g, "<B >$ & </B> ");
Alert (str1 );
All 0: 39... Write it here.

Download the regular expression tool software (password: RegEx): RegEx buddy 2.06.zip
For examples I have written, see JScript syntax highlighting (simplified code)

Here are some examples of msdn:

function matchdemo ()
{< br> var s;
var Re = new Regexp ("d (B +) (D )", "ig");
var STR = "cdbbdbsbdbdz";
var arr = re.exe C (STR);
S = "$1 contains: "+ Regexp. $1 + "\ n";
S + = "$2 contains:" + Regexp. $2 + "\ n";
S + = "$3 contains:" + Regexp. $3;
return (s);
}< br> function regexptest ()
{< br> var ver = Number (scriptenginemajorversion () + ". "+ scriptengineminorversion ()
If (ver> = 5.5) {
var src = "The rain in Spain falls mainly in the plain. ";
var Re =/\ W +/g;
var arr;
while (ARR = re.exe C (SRC ))! = NULL)
Print (ARR. index + "-" + arr. lastindex + "\ t" + ARR);
}< br> else {
alert ("You need a newer version of JScript for this to work ");
}< BR >}

Function matchdemo ()
{
VaR s; // declare variable.
VaR Re = new Regexp ("d (B +) (D)", "ig"); // regular expression pattern.
VaR STR = "cdbbdbsbdbdz"; // string to be searched.
VaR arr = re.exe C (STR); // perform the search.
S = "$1 returns:" + Regexp. $1 + "\ n ";
S + = "$2 returns:" + Regexp. $2 + "\ n ";
S + = "$3 returns:" + Regexp. $3 + "\ n ";
S + = "input returns:" + Regexp. Input + "\ n ";
S + = "lastmatch returns:" + Regexp. lastmatch + "\ n ";
S + = "leftcontext returns:" + Regexp. leftcontext + "\ n ";
S + = "rightcontext returns:" + Regexp. rightcontext + "\ n ";
S + = "lastparen returns:" + Regexp. lastparen + "\ n ";
Return (s); // return results.
}
Document. Write (matchdemo ());
From http://www.knowsky.com/339275.html

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.