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=?";
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.
string Fixed = Regex.Replace( MyString, @"DATE=2\d{7}", "DATE=?" );
或者,使用正向后看
Replace( MyString, @"(?<=DATE=)2\d{7}", "?" );
A regex that matches the entire string would probably be ideal for preventing SQL injection attacks. To accomplish this you will use the start of line ( ^
) and end of line ( $
) characters.
This will match something which is 5 or 6 digits long, and capture everything besides the first.
^([0-9])([0-9]{4,5})$
If you want to capture something that starts with 2, and is always 6 digits long; you could use 2
instead of the character class:
^(2)([0-9]{5})$
This technique will not allow you to use the replace method directly, you will need to extract the capture groups 1 and 2, replace all the characters in group 2 with ?, and then concatenate them. Something like:
matcher.group(1) + Regex.replace(m.group(2) , ".", "?")
Again, not carefully matching the entire string will result in SQL injection.
The input, (DELETE * FROM Users Where 1=1) 200000
, would match these regex, and be merrily inserted into your SQL query as: (DELETE * FROM Users Where 1=1) 2?????
You could use the Regex replace method:
string oldstring = "20120101";
string newstring = Regex.Replace(oldstring, @"^2[0-9]{7}", "?");
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.