Jeff Brady
Jeff Brady

Reputation: 1498

How do I replace unknown characters in a string? Wildcard?

I have a string .. let's say:

string MyString = "SELECT Stuff FROM Table WHERE Code = "Foo" AND DATE=20120101";

I want to replace 20120101 with a ?. But, the 20120101 string I search for won't always be the same. It will always start with a 2, and always contain 8 characters. It may be 20121225, 20130510, etc.

Can I use wildcards somehow? As in:

string Fixed = MyString.Replace("2*******", "?");

What I'm looking for is this result:

MyString = "SELECT Stuff FROM Table WHERE Code = "Foo" AND DATE=?";

Upvotes: 1

Views: 5779

Answers (4)

MikeM
MikeM

Reputation: 13641

string Fixed = Regex.Replace( MyString, @"DATE=2\d{7}", "DATE=?" ); 

Or alternatively, using a positive look-behind

 Replace( MyString, @"(?<=DATE=)2\d{7}", "?" ); 

Upvotes: 3

itsme86
itsme86

Reputation: 19496

You can use RegEx:

Regex.Replace(input,@"DATE=""\d*""", "?");

However, if this is a SQL query, it would be better to use a parameterized query to avoid SQL injection attacks and so forth. It's the industry standard way of doing these kinds of things.

Upvotes: 4

Chris
Chris

Reputation: 707

So is this what you are looking for?

string MyString = "SELECT Stuff FROM Table WHERE Code = {0} AND DATE={1}";

This will allow you to use the same string with whatever you want in {0} and {1} with something like:

String.Format(MyString, codeString, dateString);

You can reuse the query string with whichever parameters you'd like.

Upvotes: 0

Alex
Alex

Reputation: 94

You could use the Regex replace method:

    string oldstring = "20120101";
    string newstring = Regex.Replace(oldstring, @"^2[0-9]{7}", "?");

Upvotes: 0

Related Questions