Posted In: Java Core, String

How to replace string inside curly brackets

Three possible ways
1. Use replace function. In this case do not escape curly brackets
2. Use replaceAll function. In this case escape curly brackets because replaceAll uses regular expression
3. Use java.text.MessageFormat class if string to replace is like {0}, {1}, {2}

This code snippets were useful while testing Spring Rest URLs with a @PathVariable

String body = mockMvc.perform(get("/services/v1/users/{userCode}/".replaceAll("\\{userCode\\}","MYUSERCODE")

package com.javausecase.string;

import java.text.MessageFormat;

public class Replace {
	public void example1() {
		String curlyString = "{userCode}";
		System.out.println(
		        curlyString.replace("{userCode}", "MYUSERCODE"));
	}

	public void example2() {
		String curlyString = "{userCode}";
		System.out.println(
		        curlyString.replaceAll("\\{userCode\\}", "MYUSERCODE"));
	}

	public void example3() {
		String curlyString = "{0}";
		MessageFormat messageFormat = new MessageFormat(
		        curlyString);
		Object[] testArgs = { "MYUSERCODE" };
		System.out.println(messageFormat.format(testArgs));
	}

	public static void main(String a[]) {
		Replace replace = new Replace();
		replace.example1();
		replace.example2();
		replace.example3();
	}
}

Tags:

by , on October 21st, 2018