Color console output and console Output Using Regular Expressions

Source: Internet
Author: User
Tags return tag expression engine

Color console output and console Output Using Regular Expressions

Recently, I have been busy with less secondary development and encountered many requirements for outputting color text to the console. I flipped through my colleague's code and found that I had to spell escape strings myself or use some third-party libraries that were not very easy to use. According to your own taste, a good third-party library should meet the following requirements: You must support a wide range of color settings, while setting colors cannot be too cumbersome, and support the console. log wildcard expression to reduce the work of String concatenation. Similar to the syntax of cli-color and colors, the following methods are used to set the string color:

// colorsconsole.log("this is an error".error);// cli-color console.log(clc.red('red') + ' plain ' + clc.blue('blue'));

If the color of the string is large and the string contains dynamic data, a large amount of string spelling is required, which is ugly and error-prone. Therefore, this method is ignored directly.

Since these ready-made databases are not easy to use, simply write one by yourself. Html is the most commonly used front-end. Inspired by the html syntax, it is intended to set the character color in the form of tags rather than the method. For example, to output text in red or green colors, you can use the following method:Foo.log('<red>red color <green>green color</green></red>'). This method has two advantages: First, it facilitates the presentation of rich colors, especially color nesting. If cli-color is used to express the nesting of multiple colors, it is estimated that the spelling of strings will make you want to vomit. Second, the memory method name and the spelling string are omitted.

Is this design easy to implement? Before answering this question, let's talk about how to implement color output. Color text output to the console mainly uses the escape characters (ansi Escape Character Table) in ANSI ). Some of the many escape characters set the rendering method on the console. The output control adopts the following syntax to declare:\x1b[nm. The value of x1b is 27, which indicates escape characters in the ASC code table. The following [nm is the mode setting, [and m are constants, and n is the variable. You can set different output settings by setting N values. The following are common N values.

  • The text is displayed in dark color at the beginning of 0. The text color is the default color set by the user on the console, which is generally white.
  • 1. The text is displayed in the highlighted mode. The text color is the default color of the console set by the user. It is generally white.
  • 30 ~ 27 text is displayed in black, red, green, yellow, blue, pink, cyan, and white colors.

Note: These output settings will not only take effect for the current output, but will continue to take effect until new settings or the console exits! Therefore, you must remember to reset the color settings when using them, so as not to affect the subsequent console output. The following demo is used to test the functions of these escape characters. Note that the statement that draws the red line does not have any settings for the output, but the previous setting is still used because the console color is set in the previous command.

After describing so much, I can finally answer the above question: is this design easy to implement? The answer is: very simple. We only need to use this to process three types of strings: Escape Character, color start tag, and color end tag. The processing policy is also simple:

  • If an escape character starting with a slash is encountered, the character following the slash is directly returned.
  • When the start Tag is encountered, check whether it is a supported color. If not supported, it is returned without processing as is. If supported, the return tag corresponds to the color escape character, and press the color escape character to stack.
  • When an end Tag is encountered, check whether it is a supported color. If not, it is not returned as is. If supported, the stack is played and the Escape Character corresponding to the top color of the stack is returned. If the stack is empty, the default color is used.
  • All other situations are not handled and returned as is (this step is mainly to prevent unexpected matching, which should not be used in this example. Keep it for the sake of insurance ).
  • To prevent the user label from being closed and affecting other console output, set the color of the last row to the default color.

This part of logic has been closed and released to npm's rich-console module. The following shows the specific implementation code and demo running result. By the way, ANSI also supports many escape content, such as setting the background color, bold, and underline. However, these support is not good, and many of them are not supported by animals, in addition, these functions are rarely used, so these functions are intentionally ignored.

/*** Obtain the console output template with color escape characters. * @ param {String} tmpl template String containing tags * @ param {boolean} whether isBright is highlighted, default false * @ return {String} * @ public */function getRichTmpl (tmpl, isBright) {if (typeof tmpl = 'object') {return tmpl;} var fontStyle = isBright = true? '\ U001b [1m': ''; var ESCAPES = {black: (fontStyle + '\ u001b [30m'), red: (fontStyle +' \ u001b [31m '), green: (fontStyle + '\ u001b [32m'), yellow: (fontStyle +' \ u001b [33m'), orange: (fontStyle + '\ u001b [33m '), blue: (fontStyle + '\ u001b [34m'), pink: (fontStyle +' \ u001b [35m'), cyan: (fontStyle + '\ u001b [36m '), white: (fontStyle + '\ u001b [37m'), noColor:' \ u001b [0m'} var NO_COLOR = ESCAPES. NoColor; var styleStack = []; var reg = new RegExp (('(\\\\.) '// Escape Character expressed by \ +' | <(\ w +)> '// style start tag +' | </(\ w +)> '// style end tag), 'G'); var handleTag = function (str) {return str. replace (reg, function (m, $1, $2, $3) {// if it is an escape character, if ($1) {return $1. slice (1);} // if the color is not supported, ignore it directly. Otherwise, the style start character is returned and the style is pressed to the stack if ($2) {var style = ESCAPES [$2]; if (style) {styleStack. push (style); return style;} else {return m;} // If the color is not supported, ignore it directly. Otherwise, the current style will pop up from the Style Stack and return the // stack top style, if the stack is empty, the system will return the default style if ($3) {if (ESCAPES [$3]) {styleStack. pop (); var len = styleStack. length; var topStyle = len> 0? StyleStack [len-1]: null; return (topStyle? TopStyle: NO_COLOR);} else {return m ;}// others return m ;}) + NO_COLOR; // The last two Resets are used to prevent the user's tag from being closed and then polluting the entire console output}; return handleTag (tmpl);}/*** output the color text to the console. * @ param {String} cont * @ example * showColorText (* '<red> % s <green> % s </green>! </Red> ', * 'hello', * 'wold' *); * @ public */function output (cont) {// if the user inputs an object, call the console of the system to output the object structure if (typeof cont = 'object') {console. log (cont); return;} var moreArgs = []. slice. call (arguments, 1); moreArgs. unshift (getRichTmpl (cont); console. log. apply (console, moreArgs);}/*** output error information to the console in red. * @ param {String | Object} cont * @ param {Object ...} * @ public */function outputError (cont) {if (typeof cont = 'object') {console. log (cont);} else {var moreArgs = []. slice. call (arguments, 1); moreArgs. unshift ('<red>' + cont + '</red>'); output. apply (null, moreArgs) ;}} module. exports = {getRichTmpl: getRichTmpl, error: outputError, log: output}

C # How does the console program output color fonts?

Console. Title = "131"; // set the Title of the Console window
Console. ForegroundColor = lelecolor. Red; // set the font color to Red.
Console. BackgroundColor = lelecolor. Green; // set the black screen to a Green screen, that is, the background color.
If you want a function, it's nothing more

Public static void WriteLine (string msg, ConsoleColor forecolor = ConsoleColor. Red, ConsoleColor backcolor = ConsoleColor. Black)
{
Console. ForegroundColor = forecolor;
Console. BackgroundColor = backcolor;
Console. WriteLine (msg );
Console. ForegroundColor = ConsoleColor. Gray;
Console. BackgroundColor = ConsoleColor. Black;
}

WriteLine ("hell0") is called directly; // The default value is the red letter.
Or WriteLine ("hell0", ConsoleColor. Green );

How to use regular expressions

In Sun's Java JDK 1.40, Java comes with a package that supports regular expressions. This article introduces how to use the java. util. regex package.

It can be roughly estimated that, except for the occasional use of Linux, other Linu x users will encounter regular expressions. Regular Expressions are extremely powerful tools and flexible in string mode-matching and string mode-replacement. In the Unix world, regular expressions have almost no restrictions. It is certainly widely used.

The regular expression engine has been implemented by many common Unix tools, including grep, awk, vi and Emacs. In addition, many widely used scripting languages also support regular expressions, such as Python, Tcl, JavaScript, and the most famous Perl.

I used to be a Perl hacker long ago. If you are the same as me, you will be very dependent on these powerful text-munging tools at hand. In recent years, like other program developers, I have been paying more and more attention to Java development.

Java, as a development language, has many recommendations, but it has never provided its own support for regular expressions. Until recently, with the help of third-party class libraries, Java began to support regular expressions, but these third-party class libraries are inconsistent, have poor compatibility, and are poorly maintained. This shortcoming has always been a huge concern for me to choose Java as the primary development tool.

You can imagine how happy I am to know that Sun's Java JDK 1.40 contains java. util. regex (a fully open and built-in Regular Expression package! It is funny to say that I spend some time exploring this hidden gem. I am surprised that a major improvement such as Java (with the java. util. regex package included) is not made public much ?!

Recently, Java has jumped into the world of regular expressions. The java. util. regex package also has its advantages in regular expression support. In addition, Java also provides detailed instructions. As a result, the mysterious regex of zookeeper is gradually opened. Some regular expressions (perhaps the most significant difference is that the character library is incorporated) cannot be found in Perl.

The regex package contains two classes: Pattern and Matcher ). The Pattern class is used to express and state the objects in the search mode. The Matcher class is the objects that really affect the search. Add a new exception class, PatternSyntaxException. When an illegal search mode is encountered, an exception is thrown.

Even if you are familiar with regular expressions, you will find that using regular expressions in java is quite simple. One thing to note is that for the Perl enthusiasts who are spoiled by Perl's single-line matching, when using the java regex package for replacement operations, it will be more time consuming than they used previously.

The limitations of this article are not a complete tutorial on regular expression usage. If you want to learn more about Regular Expressions, read the Mastering Regular Expressions of Jeffrey Frieldl, which is published by o'reilly Publishing House. Here are some examples to teach readers how to use regular expressions and how to use them more simply.

It may be complicated to design a simple expression to match any phone number, because there are many situations in the phone number format. Select a valid mode for all instances. For example: (212) 555-1212,212 -555-1212 and 212 555 1212, some people will think they are equivalent.

First, let's construct a regular expression. For the sake of simplicity, a regular expression is first formed to identify the telephone numbers in the following format: (nnn) nnn-nnnn.

Step 1: create a pattern object to match the above sub-string. After the program runs, you can make the object generic if needed ....... Remaining full text>

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.