Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom pattern layout [closed]

I want to generate a string according to given pattern. Let's suppose:

  • %i denotes for incremental number
  • %.3r denotes for a random number with 3 characters
  • %dd denotes current day
  • %mm denotes current month
  • %yyyy denotes current year

Then, for example

IBM_%.3r => IBM_233, IBM_765..
ID_%i => ID_0, ID_1, ID_2...
%dd/%mm/%yyyy => 14/03/2014
%dd%mm%yyyy_interface.log => 14022014_interface.log

Please let me know whether there are any existing java library for this. Otherwise, what is the correct way to implement this ?

like image 981
John Smith Avatar asked Dec 01 '25 03:12

John Smith


1 Answers

According to my knowledge there is no such libraries exist .

But you can use this code instead :

CODE

  public class RegexText {
  static int i=0;
  public static void main(String[] args) {   
      String lines[]={"IBM_%.3r", "ID_%i","%dd/%mm/%yyyy","%dd%mm%yyyy_interface_%i_%i.log","ID_%i"};     
      for(String line: lines){
          System.out.println(randomGenerate(line));
      }
   }

   public static boolean matches(String line, String regex){
       return line.matches(".*"+Pattern.quote(regex)+".*");    
   }
   public static String  randomGenerate(String line){
       Date date=new Date();
       int day=date.getDate();
       int month=date.getMonth()+1;
       int year=date.getYear()+1900;   
       while(matches(line, "%i"))
           line=line.replaceFirst("%i",""+(i++));
       while(matches(line, "%.3r"))
           line=line.replaceFirst("%.3r",""+gen3DigitRand());     
       line=line.replaceAll("%dd",""+to2Digit(day));
       line=line.replaceAll("%mm",""+to2Digit(month));
       line=line.replaceAll("%yyyy",""+year);      
       return line;

   }

   public static int gen3DigitRand(){
       int num=0;
       while(String.valueOf(num).length()!=3)          
           num=(int) (Math.random()*1000);
       return num;
   }
   public static String to2Digit(int num){
       if(num<10)
           return "0"+num;
       return num+"";

   }
}

OUTPUT

IBM_904
ID_0
14/02/2014
14022014_interface_1_2.log
ID_3
like image 179
Sujith PS Avatar answered Dec 03 '25 02:12

Sujith PS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!