【问题标题】:How to replace string with regex in Java or Clojure如何在 Java 或 Clojure 中用正则表达式替换字符串
【发布时间】:2015-03-19 20:11:38
【问题描述】:

我有一些这样的字符串:

"this is a string like #{aa} and#{bb}. "
"#{cc}this is another str#{dd}ing..."

我想像这样更改这些字符串:

"this is a string like ? and?." "aa" "bb"
"?this is another str?ing..." "cc" "dd"

我尝试使用正则表达式来拆分这些字符串,但失败了。

我该怎么办?

【问题讨论】:

    标签: java regex clojure


    【解决方案1】:

    您可以使用这样的正则表达式替换字符串:

    #\{(.*?)\}
    

    Working demo

    然后您必须从捕获组中获取内容并将其连接到您的字符串。我把逻辑留给你:)

    【讨论】:

      【解决方案2】:

      你可以这样试试:

      final String regex = "#\\{(.*?)\\}";
      final String string = "ere is some string #{sx} and #{sy}.";
      final String subst = "?";
      
      final Pattern pattern = Pattern.compile(regex);
      final Matcher matcher = pattern.matcher(string);
      
      while (matcher.find()) {
          System.out.print(matcher.group(1) + " ");
      }
      
      final String result = matcher.replaceAll(subst);
      System.out.println(result);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-25
        • 1970-01-01
        • 2019-12-02
        • 1970-01-01
        • 2010-10-04
        • 1970-01-01
        • 2021-10-07
        • 1970-01-01
        相关资源
        最近更新 更多