简体   繁体   中英

Regex to replace part of a query string with literals

I have a slight problem in that I am passing several SQL Server Like queries (which I don't have control over) in my .Net application and I need to escape some of the characters to make them literals for the database.

For example, suppose the field I am trying to query looks something like:

This_is [a] long_text field with [literal] characters in it

And my query looks something like this:

SELECT * FROM [MyTable] where [MyField] Like 'This_% [literal]%'

Now, this should get that data, the challenge is that the _ and [ characters are not seen by SQL Server as the literal characters, so I have to update my query to:

SELECT * FROM [MyTable] where [MyField] Like 'This[_]% [[]literal]%'

And then it works.


So, my question is that I would like to write a VB.Net function that uses RegEx to find the Like part of the statement and then to replace the characters.

Something along the lines of:

Public Function ConvertQuery(strSQL as string)

... Some kind of Regex that searches for the word "Like" 
    and then takes everytihng between the 2 "'" characters
    Then replaces the "_" with "[_]" and "[" with "[[]"

Return ChangedString
End Function

I know I am giving REALLY bad details, I know what i want, I just can't figure out how to do it with RegEx.

ALSO, if there is a smarter way to do this with SQL Server Like statments, please also let me know!!!

Thanks!!

Seeing that C# tag, I assume you are OK with an answer in C#.

string input = "This_is [a] long_text field with [literal] characters in it";
var output = Regex.Replace(input, @"[_\[]","[$0]");

EDIT

string input = "SELECT * FROM [MyTable] where [MyField] Like 'This_% [literal]'";
var output = Regex.Replace(input, @"(?<=Like[ ]*\'.+?)[_\[]", "[$0]");

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM