Skip to content
Advertisement

How to replace all substrings?

I want to replace all the text within brackets to uppercase letters for any String object. For example if the text is – Hi (abc), how (a)re (You)?" , output should be – Hi ABC, how Are YOU? . I tried to use StringUtils.SubstringBetween(), but that replaces only the first substring between (). Using regex, I suppose the group() method requires the count of such substrings. What is the correct direction to be taken?

Advertisement

Answer

Since Java 9 we can use Matcher.replaceAll​(Function<MatchResult,String> replacer)

String str = "Hi (abc), how (a)re (You)?";

Pattern p = Pattern.compile("\((.*?)\)"); //matches parenthesis and places 
                                            //content between them in group 1
String replaced = p.matcher(str)
        .replaceAll(match -> match.group(1).toUpperCase()); //replace each match with
                                            //content of its group 1 in its upper case 

System.out.println(replaced);

Output: Hi ABC, how Are YOU?

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement