-4

This is my input String:

String content = "Hello [To:admin1] Admin 1 , Good Morning [To:user2] 
                 Admin 1, GoodNight [To:user1] Admin 1";

I want to convert this to:

"Hello [To] Admin 1 , Good Morning [To] Admin 1, GoodNight [To] Admin 1"

I am trying to use Regular Expressions but I not able to.

I want replace the text [To:xxxx] with [To]

Please suggest what can be done.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
cheng
  • 1,196
  • 2
  • 12
  • 16

3 Answers3

5

You can use this :

String st = "Hello [To:admin1] Admin 1 , Good Morning [To:user2] Admin 1, GoodNight [To:user1] Admin 1";
st = st.replaceAll("\\[To:.*?\\]", "[To]");
System.out.println(st);

This will replace every thing between [To: and ] to [To], and this will show you :

Hello [To] Admin 1 , Good Morning [To] Admin 1, GoodNight [To] Admin 1
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
2

Just alternative solution by java regex.

    String st = "Hello [To:admin1] Admin 1 , Good Morning [To:user2] Admin 1, GoodNight [To:user1] Admin 1";
    Pattern pattern = Pattern.compile("\\[To:[a-zA-Z0-9]*\\]");
    String result = pattern.matcher(st).replaceAll("[To]");
    System.out.println(result);
Hardy Feng
  • 459
  • 4
  • 13
1
String stringToSearch = "Hello [To:admin1] Admin 1 , Good Morning [To:user2] Admin 1, GoodNight [To:user1] Admin 1";

Pattern p = Pattern.compile("To:[\\w]+");
Matcher m = p.matcher(stringToSearch);
StringBuffer sb = new StringBuffer();
while(m.find()){
    m.appendReplacement(sb,"To");
}
m.appendTail(sb);
System.out.println(sb.toString());
Avaneesh
  • 162
  • 5