-1

I have pattern like '{YY}-{MM}-{SEQNO}'. I want to replace above string by dynamic value.

For example

{YY} with - 17 
{MM} with - 06
{SEQNO} WITH - 0001

What is the way to that in java?

Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94

3 Answers3

0

Use String.replace().

String template = "'{YY}-{MM}-{SEQNO}'";
template = template.replace("{YY}", "17");
template = template.replace("{MM}", "06");
template = template.replace("{SEQNO}", "0001");

(Thanks to @RealSkeptic for improvements).

Steve Smith
  • 2,244
  • 2
  • 18
  • 22
0

If you want to print like 17-06-0001 Use

System.out.printf("%S-%S-%S\n", ""+17, ""+06, ""+0001);

or If you want to print like 17-6-1 Use

System.out.printf("%d-%d-%d\n", 17, 06, 0001);
Suraj Khanra
  • 480
  • 1
  • 5
  • 23
  • What do you do when the template is changed like `{MM}/{SEQNO}-/{YY}`? –  Jun 14 '17 at 12:04
0

method one(easier method):

String a = "{YY}-{MM}-{SEQNO}";
a = a.replace("YY", "17").replace("MM", "06").replace("SEQNO", "0001");
System.out.println(a);
//Output:  {17}-{06}-{0001}

method two:

a = Pattern.compile("YY").matcher(a).replaceAll("17");
a = Pattern.compile("MM").matcher(a).replaceAll("06");
a = Pattern.compile("SEQNO").matcher(a).replaceAll("0001");
System.out.println("My Output is : " +a);
//Output:  My Output is : {17}-{06}-{0001}

Method three:

Have a look at this question -without using replace().

Blasanka
  • 21,001
  • 12
  • 102
  • 104