ReVo Blog


Friends

Friends Posts

profile for Marco Acierno at Stack Overflow, Q&A for professional and enthusiast programmers
profile for Marco Acierno on Stack Exchange, a network of free, community-driven Q&A sites
1 user(s) online
F_ACTIVE
1 guests
0 members
0 Anonymous Members
[ View Complete List ]


Last comments


Statistics
F_STATS
ReVo Blog have:
8 articles, 0 comments, 1 members,
167 total visits, 0 monthly visits

The newest member is .ReVo.


B_NORM    
view post Posted on 27/8/2014, 14:19 by: .ReVo. Reply
Passato a format la stringa da formttare e in variables le variabili con cui bisogna sostituire le corrispondenze.

CODICE
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* La classe ti permette di formattare una stringa X
* e di sostituire dei blocchi con valori di variabili.
*
* @author Marco Acierno
*/
public class Template {
   private final Pattern pattern;

   public Template(String start, String end) {
       pattern = Pattern.compile(Pattern.quote(start) + "([^}]+)" + Pattern.quote(end));
   }

   public Template() {
       this("{", "}");
   }

   public String format(String text, Map<String, String> variables) {
       Matcher matcher = pattern.matcher(text);
       /* appendReplacement e appendTail accettano solo StringBuffer */
       StringBuffer buffer = new StringBuffer();

       while (matcher.find()) {
           String key = matcher.group(1);
           String value = variables.get(key);

           if (value == null) {
               matcher.appendReplacement(buffer, "{" + key + "}");
               continue;
           }

           matcher.appendReplacement(buffer, value);
       }

       matcher.appendTail(buffer);
       return buffer.toString();
   }
}


Alcuni test-cases per capire come funziona:

CODICE
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.*;

public class TemplateTest {

   @Test
   public void testFormat() throws Exception {
       Template template = new Template();

       String text = "Hello {who}, {saluto}";
       String result = "Hello ReVo_, ok?";

     ...

Read the whole post...



Tags:
java,
jbucket-api
Comments: 0 | Views: 4Last Post by: .ReVo. (27/8/2014, 14:19)
 

Search: