How to insert multiline paragraph on console in java

Can anyone suggest a method for writing a mutli-line line string to the system console and indented this text block? I am looking for something relatively lightweight because it is only used to display help for the command line.

+6
source share
1 answer

NOTE. . The approach below does not meet the updated requirements described by @BillMan in the comments on the question. This one will not automatically wrap strings longer than the length of the console string - use this approach only if wrapping is not a problem.


As a simple option, you can use String.replaceAll() as follows:
 String output = <your string here> String indented = output.replaceAll("(?m)^", "\t"); 

If you are not familiar with Java regular expressions, it works as follows:

  • (?m) provides multi-line mode. This means that each line in output treated separately, rather than treating output as one line (which is the default).
  • ^ is a regular expression matching the beginning of each line.
  • \t forces each match of the previous regular expression (i.e. the beginning of each line) to be replaced by a tab character.

The following code is an example:

 String output = "foo\nbar\nbaz\n" String indented = output.replaceAll("(?m)^", "\t"); System.out.println(indented); 

Produces this conclusion:

  foo
	 bar
	 baz
+26
source

All Articles