-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?

3
  • 2
    String.replaceAll() Commented Jun 14, 2017 at 11:45
  • 2
    Actually, String.replace() is better, as it doesn't require regular expressions - this is more efficient and has less problems with special characters. Commented Jun 14, 2017 at 11:52
  • 1
    so the ouput must be {17}-{06}-{0001} or 17-06-0001 ??? Commented Jun 14, 2017 at 11:53

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

2 Comments

The replacement should include the braces. You don't want to get {17}-{06}-{0001}. Also, you probably don't want to replace the template itself.
@RealSkeptic Thanks. I wasn't sure if OP wanted the braces or not.
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);

1 Comment

What do you do when the template is changed like {MM}/{SEQNO}-/{YY}?
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().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.