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(); } }
- Apache (13)
- Build Tools (2)
- Gradle (2)
- Caching (1)
- cpanel (1)
- cURL (1)
- Database (7)
- Hibernate (5)
- Java Core (38)
- Java Script (15)
- Bootstrap (1)
- File Upload (7)
- jQuery (3)
- React (3)
- JEE (13)
- JSON (41)
- GSON (13)
- Jackson 1X (1)
- Jackson 2X (12)
- jsoniter (1)
- Logging (2)
- Apache Commons Logging (1)
- Apache Log4J (1)
- Logback (1)
- SLF4J (1)
- MongoDB (1)
- OS (1)
- Linux (1)
- Security (5)
- Server (4)
- Tomcat (4)
- Service (2)
- Micro (2)
- Spring (46)
- Pattern (2)
- Spring Boot (20)
- Spring Data (4)
- Spring MVC (8)
- Spring REST (13)
- Spring Security (7)
- Testing (11)
- XML (5)
- JDOM XML Parser (1)