user710502
user710502

Reputation: 11471

Working with strings and replace

what can I use to replace the string if its in the following format

   I' have a "car" that runs very well

So basically i have a search function

and if they just type ' it wasnt finding it so i did

mySearchWord.Replace("'", "''") 

and then it found it but now what if there is an ' and " in the same sentence or word, how can i check for both in mySearchWord ?

because for both cases i would do something like

    mySearchWord.Replace("'", "''") 

mySearchWord.Replace("\"", "\"") //have no idea about this one

or something like that, is there a way to do it at once?

I think someone below is pointing me in the right direction, i just need to be able to pass apostrophes or quotation marks to my search but it was throwing an error maube because when passed, just as in sql, you would need to escape a quotation or apostrophe

Upvotes: 0

Views: 175

Answers (2)

Mikael Östberg
Mikael Östberg

Reputation: 17146

This actually replaces both at once:

string text = "I' have a \"car\" that runs very well";
string pattern = "['\"]";
var result = Regex.Replace(text, pattern, m => (m.Value == "'") ? "''" : "\"\"");

I should explain.

This is using a method called Regular Expressions. The pattern variable is the regular expression pattern which is used to match things in the string text. In this case the pattern states that it should match all ' and " characters in the text. The pattern [abc] would match all a, b and c characters.

Regular Expressions seem complex at first, but is very powerful.

You find the Regex class in the System.Text.RegularExpressions namespace.

Here is the documentation for it: http://msdn.microsoft.com/en-us/library/c75he57e(v=VS.100).aspx

The code m => (m.Value == "'") ? "''" : "\"\"" is a Lambda expression, which is a short hand to the Delegate MatchEvaluator (docs).

Upvotes: 3

Senad Meškin
Senad Meškin

Reputation: 13756

mySearchWord.Replace("''", "[{just_to_replace}]").Replace("'", "''").Replace("[{just_to_replace}]", "''");

cool, ain't it.

Upvotes: 2

Related Questions