savior
savior

Reputation: 832

How to replace string with regex in Java or Clojure

I have some String like this:

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

I want to change these String like this:

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

I tried to use regular expressions to split these string and failed.

What should I do?

Upvotes: 0

Views: 83

Answers (2)

shibli049
shibli049

Reputation: 538

You can try like this:

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

Upvotes: 0

Federico Piazza
Federico Piazza

Reputation: 30995

You can replace the string using a regex like this:

#\{(.*?)\}

Working demo

Then you have to grab the content from the capturing group and concatenate it to your string. I leave the logic for you :)

Upvotes: 1

Related Questions