Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape braces (curly brackets) in a format string in .NET

How can brackets be escaped in using string.Format?

For example:

String val = "1,2,3" String.Format(" foo {{0}}", val); 

This example doesn't throw an exception, but it outputs the string foo {0}.

Is there a way to escape the brackets?

like image 729
Pop Catalin Avatar asked Sep 18 '08 10:09

Pop Catalin


People also ask

How do you escape curly braces in HTML?

Use "{{ '{' }}") to escape it.)

Do curly braces need to be escaped in regex?

To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.


2 Answers

Yes, to output { in string.Format you have to escape it like this: {{

So the following will output "foo {1,2,3}".

String val = "1,2,3"; String.Format(" foo {{{0}}}", val); 

But you have to know about a design bug in C# which is that by going on the above logic you would assume this below code will print {24.00}:

int i = 24; string str = String.Format("{{{0:N}}}", i); // Gives '{N}' instead of {24.00} 

But this prints {N}. This is because the way C# parses escape sequences and format characters. To get the desired value in the above case, you have to use this instead:

String.Format("{0}{1:N}{2}", "{", i, "}") // Evaluates to {24.00} 

Reference Articles

  • String.Format gotcha
  • String Formatting FAQ
like image 27
Guru Kara Avatar answered Oct 26 '22 15:10

Guru Kara


For you to output foo {1, 2, 3} you have to do something like:

string t = "1, 2, 3"; string v = String.Format(" foo {{{0}}}", t); 

To output a { you use {{ and to output a } you use }}.

Or now, you can also use C# string interpolation like this (a feature available in C# 6.0)

Escaping brackets: String interpolation $(""). It is new feature in C# 6.0.

var inVal = "1, 2, 3"; var outVal = $" foo {{{inVal}}}"; // The output will be:  foo {1, 2, 3} 
like image 139
Jorge Ferreira Avatar answered Oct 26 '22 15:10

Jorge Ferreira