【问题标题】:How to replace all substrings?如何替换所有子字符串?
【发布时间】:2022-01-11 06:08:54
【问题描述】:

我想将任何String 对象的括号内的所有文本替换为大写字母。例如,如果文本是 - Hi (abc), how (a)re (You)?" ,则输出应该是 - Hi ABC, how Are YOU? 。我尝试使用StringUtils.SubstringBetween(),但它只替换了() 之间的第一个子字符串。 使用regex,我想group() 方法需要计算此类子字符串的数量。正确的方向是什么?

【问题讨论】:

    标签: java string replace


    【解决方案1】:

    从 Java 9 开始我们可以使用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);
    

    输出:Hi ABC, how Are YOU?

    【讨论】:

      猜你喜欢
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 2016-03-16
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      • 2011-09-29
      相关资源
      最近更新 更多