如何在Java或Clojure中用正则表达式替换字符串

时间:2015-03-19 20:11:38

标签: java regex clojure

我有一些像这样的字符串:

"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"

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

我该怎么办?

2 个答案:

答案 0 :(得分:1)

您可以使用如下正则表达式替换字符串:

#\{(.*?)\}

<强> Working demo

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

答案 1 :(得分:0)

您可以尝试这样:

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);