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.
-
\$\begingroup\$ Related Stack Overflow question \$\endgroup\$200_success– 200_success2015年05月26日 21:36:30 +00:00Commented May 26, 2015 at 21:36
-
\$\begingroup\$ Do you want to remove only matched curly braces? \$\endgroup\$Donald.McLean– Donald.McLean2015年05月26日 23:17:15 +00:00Commented May 26, 2015 at 23:17
4 Answers 4
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]);
}
}
-
\$\begingroup\$ it's OK, if you feel that i was wrong. \$\endgroup\$Sajidkhan– Sajidkhan2015年05月26日 23:20:14 +00:00Commented May 26, 2015 at 23:20