A detailed explanation of the usage of the regular expressions in JScript (with examples: JScript does highlighting)

Source: Internet
Author: User
Tags object contains expression html tags key words regular expression return variable
js|jscript| Display | detailed | grammar | regular

Oh, first wordy a few words, last year, using C # to do a syntax highlighting small things, according to the information in the configuration file to format the code to HTML, so that it can be displayed on the Web page and editor of the same syntax elements highlighting the effect and support code folding. Yes, just like what I saw in the blog park. Because I was using MSN space, it did not provide this function, had to write a slightly.

I am using C # to write, the first use of the super cumbersome for,while,switch,if and other basic statements to judge the key words and so on, we mo jokes, I was stupid at that time did not know the regular expression is what, so can only use this soil method, of course, the soil method still has effect, Just a function of lengthy code, I am afraid it is very difficult to maintain later, I thought that other software can not be so written it, so to Google search for a while, found some syntax highlighting code and open source projects, open up a look ... Halo, each is so complex, said the most I do not like to do is to see someone else's code, I am not pretentious, really look at others code is very faint, unless there is a very detailed document description, otherwise I aim at two eyes do not want to see, the most is to see how the other interface to write, and then guess how his internal implementation.

Although the search for things not much help, but still let me know the regular expression of this dongdong, specifically forget where to see the. At that time began to study the regular expression while transforming my "junk". Then not long in the blog to reopen Bo, and finally opened the blog with the syntax of the garden to highlight the function, so they write a code HTML highlighting the east has lost a major motivation. Second, the syntax highlighting module in C # can only be run on the server side, or on the WinForm program, and I finally want to get the HTML code to display on the page, I think the client script is best for this job. Unfortunately, I do not know much about JS ... Later this time and fooling around, and did not improve the grammar highlight module.

Yesterday overtime night overtime to return home, originally intended to continue to study the UML modeling, then remembered that the company has a module needs to be able to remove all the HTML tags in the database return results, I open the regular expression tool Regexbuddy. As a result, Regexbuddy's help document saw the simple teaching of JScript using regular expressions, and then curiosity began to open the UltraEdit-32 to write simple JavaScript experiments.

My test process here is not much nonsense to repeat, because many places are repeated experiments around a lot of detours, here directly to the test summarized in the use of JScript.

End of the nonsense, the following into the business!

The Prime Minister speaks of JScript's regular expression object RegExp.

The class name in JScript that provides a regular expression operation is regexp, and you can instantiate an object of regexp type in two ways.

Method one, constructor instantiation:

var Myregex = new RegExp ("\\w+", "IgM");
\w+ is the actual regular expression, note that the first \ for escape, IgM, respectively, to ignore case, global search, multiline search, this will explain
Method two, Direct assignment method:

var myregex =/\w+/igm;
The effect is the same as the previous statement, except that you do not need to use the transfer character, the original regular expression is what it looks like, IgM and the previous example of the IgM effect
The specific way to see how people like, personally feel the second way to write is better to read some, Regexbuddy help document is also recommended the second way. The RegExp object contains some of the following actions:

EXEC (String str): Performs a regular expression match and returns the result of the match, according to the example given by MSDN, the exec executes every time from the last direct match end position, and the value returned appears to be the Rerexp object. The explanation given by Regexbuddy is to return an array, but without giving a detailed example, I think it is more reliable based on the test results.

Compile (string regex, String flags): Precompiling a regular expression to make it run faster, and after testing it does have a significant increase in efficiency after precompilation. The Regex argument is a regular expression, and flags can be a combination of the following 3 values: g– Global Search, my test result is that no G-flag can only match the first qualifying string I-compact ignore case m– multiple-line search, it seems that the default is a multiline search

Test (String str): If STR matches a regular expression that returns True, False is returned, and the match method of this string-like object

The RegExp object contains some of the following properties:

Index: The position of the first matching expression in the string, initially-1
Input: Matching target for regular expressions, note is read-only
Lastindex: The position of the next match expression, in the exact words (Returns the character position where the next match begins in a searched string.) Do not know if there is no translation error, this attribute I did not use.
Lastmatch: string of last matching expression
Lastparen: The last matched substring of a match, for example, there are multiple occurrences of () grouped in the regular expression, lastparen represents the result of the last set
Leftcontext: All characters from the beginning of the target string to the starting position of the last match.
Rightcontext: All characters from the end of last match to the end of the entire destination string.
$1...$9: Represents the result of the Nth group match, which is useful in a regular expression with multiple groups ()

Next, the operation of a string object in JScript that relates to a regular expression:

Match (String regex): accepts a regular expression and returns whether the string matches this expression.
Replace (srting regex, String str): Replaces a substring matched with a regular expression with STR, a function that looks simple but still hides a more advanced usage oh, see the following example.
Example 1:

var str1 = "A:My name is Peter!\nb:hi peter!";
STR1 = Str1.replace (/peter/g, "Jack");
alert (STR1);
This example is very simple to replace the string, the power of this expression is of course not only this, if you use the skilled, you can also use it to do a lot of previous work that requires a lot of code. For example, before and after the Code keyword plus because of the highlighted HTML tags. From the previous example, it seems that replace can only replace the matching text for the new text ah, how to use it to insert tags before and after the keyword? Back to imagine, if the replacement can be used to match the results, then things are not good to do, as long as the keyword replaced by: Tag head + keyword + tag end of the line.

But how do you use regular expression matching results in replace?

At this point we need to use the "match variable", the matching variable is used to represent the result of a regular match, the following is a description of the matching variable:
$&----represents the result of all matching group matches, and last verbose, the matching group is the () Grouping of regular expressions
$$--Represents the $ character, because the matching variable uses the $ character, so you need to escape
$n--similar to the previous $1...$9, representing the result of the nth group match
$nn--very simple is the result of the NN group match
$ '--the leftcontext that was mentioned earlier, such as ABCDEFG being matched D so ABC is its leftcontext.
$ '--very close to the above don't be mistaken! , this is rightcontext, extrapolate, EFG is the example above rightcontext so now we have to do before and after the keyword insertion of the label is very simple:

var str1 = "A:My name is Peter!\nb:hi peter!";
STR1 = Str1.replace (/peter/g, "<b>$&</b>");
alert (STR1);
It's 0:39. Just write it down here.

Regular tool software download (password: regex): Regex buddy 2.06.zip
For example, please see: JScript do syntax highlighting (code streamlining)

Here are some examples of MSDN copy:

Function Matchdemo ()
{
   var s;
   var re = new RegExp ("D (b +) (d)", "IG");
   var str = "CDBBDBSBDBDZ";
   var arr = re.exec (str);
   s = "$ contains:" + regexp.$1 + "\ n";
   s = "$ contains:" + regexp.$2 + "\ n";
   s = "$ contains:" + regexp.$3;
   return (s);
}
Function Regexptest ()
{
  var ver = number (ScriptEngineMajorVersion () + "." + ScriptEngineMinorVersion ())
  if (ver >= 5.5) {
    var src = "The Rain in Spain Falls In the plain. ";
    var re =/\w+/g;
    var arr;
    while (arr = re.exec (src))!= null)
       print (Arr.index + " -"+ Arr.lastindex +" \ T "+ arr);
 }
  else{
    alert ("You need a newer version of JScript as this to work");
 }
}

function Matchdemo ()
{
var s; Declare variable.
var re = new RegExp ("D (b +) (d)", "IG"); Regular expression pattern.
var str = "CDBBDBSBDBDZ"; String to is searched.
var arr = re.exec (str); Perform the search.
s = "$ returns:" + regexp.$1 + "\ n";
S + + "$ returns:" + regexp.$2 + "\ n";
S + + "$ 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 ());

You pass by the warrior if the article has any views welcome here, we learn together, common progress.



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.