-1

So I am trying to replace the characters below from a users input which relates to a SQL column in a table.

Example: User creates a field called My(first)try. In SQL this comes up as Myfirsttry.

I am currently write code to replace the users input with our and I am stuck.

I have this so far.

  itemreplace = itemreplace.Replace("(", "");

This however, doesn't do the trick. Thoughts, comments, suggestions?

ST3
  • 8,826
  • 3
  • 68
  • 92
Xerc
  • 135
  • 2
  • 16
  • 4
    So what *does* it do? What is the result of running that line of code? – Servy Oct 11 '13 at 19:47
  • 1
    If you did the same thing again for the closing bracket would life be better? – Dan Bracuk Oct 11 '13 at 19:48
  • itemreplace is a string, right? That certainly should work. Post your actual code. I just tried that in a quick dirty console application and it properly replaces the open parenthesis with an empty string. – sab669 Oct 11 '13 at 19:50
  • 2
    This smells like your asking for a SQL injection attack... Please tell me you aren't trying to clean up input from the user and make a query out of the text... – Kevin Oct 11 '13 at 19:51
  • Basically an exact duplicate of this question from two days ago (parenthesis and all): http://stackoverflow.com/questions/19280553/how-do-i-remove-multiple-offending-characters-from-my-string – valverij Oct 11 '13 at 19:52
  • possible duplicate of [Remove characters from C# string](http://stackoverflow.com/questions/7411438/remove-characters-from-c-sharp-string) – John Saunders Oct 11 '13 at 19:53

2 Answers2

2

I feel like the real-world case is more complicated, and you're not indicating that, but to handle your example text My(first)try you could just chain the Replace statements:

itemreplace = itemreplace.Replace("(", "").Replace(")", "");

However, it seems like the real-world case is more along the lines of leveraging a Regex like this:

^[a-zA-Z0-9_@#][a-zA-Z0-9@$#_]*$

and here is a Regex 101 that would prove that.

Then using that might look like this:

var valid = Regex.IsMatch("My(first)try", pattern);

I did reference this post, What special characters are allowed in T-SQL column name?, to determine the allowed characters for a column name.

Community
  • 1
  • 1
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
  • Thanks everyone. I did try searching but I guess I had no idea what I was searching for to begin with. – Xerc Oct 11 '13 at 21:15
1

First option:

String itemreplace = new String("My(first)try");
String charsToRemove = new String[] {"(", ")"};
foreach (char c in charsToRemove)
{
    itemreplace = itemreplace.Replace(c, string.Empty);
}

Second option:

itemreplace = itemreplace.Replace("(", string.Empty).Replace(")", string.Empty);
ST3
  • 8,826
  • 3
  • 68
  • 92