# Replacing all occurrences in a String

I have a string like this :

val content = "some_text{macro1}another_text{macro2}text"


I want to replace the {macro1} and {macro2} with macro1 and macro2, i.e. just to remove the { and }.

I wrote some piece of code which works fine, but for me it seems very hard to read:

val Pattern = """\{(.*)\}""".r

Pattern.findAllIn(content).matchData.foldLeft(content) ( (newContent: String, current: Regex.Match) => {
newContent.replace(current.group(0), current.group(1))
}
)


How I can improve this code? Please note: since it's in Scala, I prefer it in the functional way.

Your desire to use the "functional way" is not well-motivated. Why do it "the functional way" when the "other way" is not only easier to read, but also common practice, and well-understood?

val stripCurly = "[{}]".r

val replaced = stripCurly.replaceAllIn(a, "")


If you want to have forced-matching of the braces consider:

val pure = """\{([^}]*)\}""".r
val pured = pure.replaceAllIn(content, "\$1")


Note the use of the "not a } inside the {}" logic in the regex.

The examples above are running here in ideone

I know nothing of Scala, and my Regex knowledge is that of the .NET flavor, so please take this with a grain of salt.

In my books, your regex produces only 1 match:

• {macro1}another_text{macro2}

You're matching an opening brace and a closing brace, but in-between, anything goes, including opening and closing braces!

To get 2 matches you could use a lazy/reluctant match for the .* part:

\{(.*?)\}


This produces 2 matches:

• {macro1}
• {macro2}

However an excluding match is a better option because it doesn't incur backtracking and thus, performs better.

I know this is late, but here's a Scala flavoured way:

Define a function that takes a string as a parameter, filters out all the characters you don't want (in this case { and }), and then returns a new string: val bracketRemover = (str:String) => str.filter(_!='{').filter(_!='}')

val targetStr = "This { should }{ not contain { } {brack{ets"

and then just call the function with your target string:

scala> val cleanString = bracketRemover(targetStr)
cleanString: String = This  should  not contain   brackets


Regarding your question, it seems that you should parse the string and remove {, } from your given string. This simple algorithm just removes the two curly braces from the string.

String a="some_text{macro1}another_text{macro2}text";
StringBuilder newString;
for(i=0; i<=a.size; i++){
if(!a.charAtIndex[i].equals({) OR !a.charAtIndex[i].equals(})){
newString.apend(a.charAtIndex[i]);
}
}

• it's OK, if you feel that i was wrong. – Sajidkhan May 26 '15 at 23:20