patternMinor
Replacing all occurrences in a String
Viewed 0 times
stringreplacingoccurrencesall
Problem
I have a string like this :
I want to replace the
I wrote some piece of code which works fine, but for me it seems very hard to read:
How I can improve this code? Please note: since it's in Scala, I prefer it in the functional way.
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.
Solution
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?
If you want to have forced-matching of the braces consider:
Note the use of the "not a } inside the {}" logic in the regex.
The examples above are running here in ideone
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
Code Snippets
val stripCurly = "[{}]".r
val replaced = stripCurly.replaceAllIn(a, "")val pure = """\{([^}]*)\}""".r
val pured = pure.replaceAllIn(content, "$1")Context
StackExchange Code Review Q#91861, answer score: 7
Revisions (0)
No revisions yet.