Skip to content
Advertisement

Replace [ ] bracket in a string

I have a string that includes brackets, [], around a number. Since this string represents my column names for a SQL database I need to remove/replace them. So far I do it in the following way:

if (stringWithBracket.Contains("[0]"))
   noBracket = data.Replace("[0]", "0");
if (stringWithBracket.Contains("[1]"))
   noBracket = data.Replace("[1]", "1");
if (stringWithBracket.Contains("[2]"))
   noBracket = data.Replace("[2]", "2");
if (stringWithBracket.Contains("[n]"))
   noBracket = data.Replace("[n]", "n");

It works fine, but it looks ugly for me since I have to do that for [1] to [20].

Is there a way to implement this “nicer” which means with less code for me?

Advertisement

Answer

You can use Regex.Replace to ensure to only extract the numbers:

var pattern = @"[(d+)]";
var replaced = Regex.Replace(stringWithBracket, pattern, "$1"); 
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement