Java uses regular expressions to implement a string template instance in the form of ${name} _java

Source: Internet
Author: User
Tags regular expression

Objective

I believe you may have encountered this situation, in the development of similar in-Station letter requirements, we often use string templates, such as

Honorable User ${name} ....

The inside ${name} can be replaced with the user's user name.

The following is a simple implementation of this function using regular expressions:

/**
  * Fills strings based on key value pairs, such as ("Hello ${name}", {name: "Xiaoming"})
  * output:
  * @param content
  * @param map
  * return
  *
 /public static string renderstring (string content, map<string, string> Map) {
  set< entry<string, string>> sets = Map.entryset ();
  For (entry<string, string> entry:sets) {
   String regex = "\\$\\{" + entry.getkey () + "\}";
   Pattern pattern = pattern.compile (regex);
   Matcher Matcher = pattern.matcher (content);
   Content = Matcher.replaceall (Entry.getvalue ());
  }
  return content;
 }

A map key-value pair is stored in, then a collection of key-value pairs is retrieved, and the collection is traversed to render the string

Instance test:

@Test public
 void Renderstring () {
  String content = "Hello ${name}, 1 2 3 4 5 ${six} 7, again ${name}.";
  map<string, string> map = new hashmap<> ();
  Map.put ("name", "Java");
  Map.put ("Six", "6");
  Content = stringhelper.renderstring (content, map);
  SYSTEM.OUT.PRINTLN (content);
 }

There are two variables that need to be replaced, name and the six corresponding values are Java and 6 respectively, and two are called at the same time name .

Results:

 
 

Summarize

The above is about Java using regular expression to implement ${name} form of the entire contents of the string template, I hope this article on the content of everyone's study or work can bring some help, if you have questions you can message exchange.

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.