How to implement the JavaScript code highlighting for regular expressions _ regular expressions

Source: Internet
Author: User

Today, I would like to change the highlight of JS color, suppressed the afternoon to suppress the regular expression of this.
The old master's long thing is a regular expression, see don't be frightened.

Copy Code code as follows:

/(\/\/.*|\/\*[\s\s]+?\*\/) | ((["'])(?:\ \.| [^\\\n]) *?\3) |\b (break|continue|do|for|in|function|if|else|return|switch|this|throw|try|catch|finally|var|while|with| case|new|typeof|instance|delete|void) \b|\b (object| array| String| number| boolean| function| regexp| date| math|window|document|navigator|location) \b|\b (true|false) \b|\b (null|undefined| NaN) \b| (?: [^\w\d]|\$) [\$\w]*| (0[xx][0-9a-fa-f]+|\d+ (?: \. \d+)? (?: [ee]\d+)?) | (?:[^\)\]\}]|^)(\/(?! \*)(?:\ \.| [^\\\/\n]) +?\/[gim]*) | [\s\s]/g

Now, we can analyze it slowly. Looking closely at this regular expression, you will find that many of the regular expressions are connected by |. Now, let's split it up and analyze it one by one.

Copy Code code as follows:

(\/\/.*|\/\*[\s\s]+?\*\/)

This is the second one, this regular expression is used to match the string. The string can be in single and double quotes, so we match either of these two. Here you need to enclose it in parentheses to indicate that it is a fetch match ("fetch" is a noun), because at the end of the place you need to match the character. At the end of the match string, you can use the back reference \ 3来 to match the character at the beginning of the string, which is the type of quotation mark at the beginning. If you count from the beginning of the entire regular expression, you will find that the parentheses outside of ["] are the third fetch match in the entire regular expression. This is the end of the string, the middle part because the string can contain the escape, so once we encounter the backslash, we skip over the character behind it, because the backslash is followed by the escape. But this is just a matching escape, so we're going to use or compute | To connect a matching not-escaped expression, which is [^\\]. But this is any character that matches a non backslash, it can contain a newline, and a string in JS is not allowed to be written as a newline. So we need to add a \ n to make it do not match line wrapping. Because we use or to connect, and the priority is very low, we need to add parentheses next to the priority. If you use normal parentheses, you will occupy a fetch match, so we want to use the (?:) To complete a non-fetch match.

Copy Code code as follows:

\b (break|continue|do|for|in|function|if|else|return|switch|this|throw|try|catch|finally|var|while|with|case| new|typeof|instance|delete|void) \b|\b (object| array| String| number| boolean| function| regexp| date| math|window|document|navigator|location) \b|\b (true|false) \b|\b (null|undefined| NaN) \b

This is the 3rd, 4, 5, 6, these are just matching some keywords, because the need for different colors so are grouped. There's nothing to say, skip it.

Copy Code code as follows:

(?: [^\w\d]|\$) [\$\w]*

This is the seventh one, and its function is to match the normal variable name. If the character of the variable name is not consumed, then the matching number will probably match the output of the number in the variable name. So this step is necessary. You will find this step without any getting a match, because the variable name color is the default color and we do not get it. According to the JS naming rules, variable names can not start with a number, so we use [^\w\d]|\$ to match the beginning of a variable. Then you can match numbers, letters, underscores, dollar signs, and any number of times. So the variable name is consumed.

Copy Code code as follows:

(0[xx][0-9a-fa-f]+|\d+ (?: \. \d+)? (?: [ee]\d+)?)

This is the eighth one that matches the numbers. Since there are two ways to express numbers, we have to write them separately. | The left side of the 16-digit notation. On the right is the normal number notation, which can include decimal and scientific notation. Since decimal and scientific notation are optional, we enclose it in parentheses followed by a question mark as an optional match.

Copy Code code as follows:

(?:[^\)\]\}]|^)(\/(?! \*)(?:\ \.| [^\\\/\n]) +?\/[gim]*)

This is the nineth one that matches the regular expression. A non-fetch match precedes the end of the non-parenthesis. Because if parentheses are present, the diagonal bar may represent a division rather than a regular expression. The following is the matching of regular expressions, similar to string matches, except for the last one [gim]*. This is the three matching pattern of the regular expression, and it belongs to the category of the regular expression, so we have to match it and get it.

Copy Code code as follows:

[\s\s]

The last one is to match all the characters that are not matched to each other, we have to match each character. Because they all need to do an HTML escape.
In this way, the long positive analysis is over. Here is an example of implementation.

Copy Code code as follows:

<style>body {font:14px/18px Consolas;} </style>
<script id= "Code" >
Read into current code
var Code=document.getelementbyid ("code"). InnerHTML;
Fixed line change browser differences, remove the line and space
Code=code.replace (/\r\n|[ \r\n]/g, "\ n"). Replace (/^\s+|\s+$/g, "");
Start Master Match
Code=code.replace (/(\/\/.*|\/\*[.\s]+?\*\/) | ( (["']) (?:\ \.| [^\\\n]) *?\3) |\b (break|continue|do|for|in|function|if|else|return|switch|this|throw|try|catch|finally|var|while|with| case|new|typeof|instance|delete|void) \b|\b (object| array| String| number| boolean| function| regexp| date| math|window|document|navigator|location) \b|\b (true|false) \b|\b (null|undefined| NaN) \b| (?: [^\w\d]|\$) [\$\w]*| (0[xx][0-9a-fa-f]+|\d+ (?: \. \d+)? (?: [ee]\d+)?) | (?:[^\)\]\}]|^)(\/(?! \*)(?:\ \.| [^\\\/\n]) +?\/[gim]*) | [. \s]/g,function () {
var a,l,i,s;
a=arguments;
Where the loop matches to
for (i=1;i<=9;i++) if (S=a[i]) {
S=htmlencode (s);
Each gets a matching location with a different color.
switch (i) {
Case 1://Notes
Return S.fontcolor ("#998877"). italics ();
Case 2:case 3://String
Return S.fontcolor ("#AA5544");
Case 4://Keywords
Return S.fontcolor ("#333388");
Case 5://Built-in objects
Return S.fontcolor ("#5555AA");
Case 6://Boolean value
Return S.fontcolor ("#DD6600");
Case 7://Null value
Return S.fontcolor ("#BB4433");
Case 8://Number
Return S.fontcolor ("#CC3322");
Case 9://Regular Expression
This is special, it matches and gets a little different.
There is a non-fetch match in front of the match, so we want to keep the part that does not get the match
Return HtmlEncode (A[0]). Replace (S,s.fontcolor ("#33AA33"));
};
};
Escape output directly without getting a match
Return HtmlEncode (a[0]);
});

Output results
document.write (code);

Escape function for HTML
function HtmlEncode (e) {
var i,s;
For (I in s={
"&":/&/g, "" ":/"/g, "'":/'/g,
"<":/</g, ">":/>/g, "<br/>":/\n/g,
""://g, "":/\t/g
}) E=e.replace (s[i],i);
return e;
};
</script>

Because today in the rush of this article, there is no time to do this code optimization. There should be a lot of small holes, but that's the whole idea. In this way, whether it is JS or any other language, code highlighting can be directly matched.

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.