[英]Regex to replace part of a query string with literals
我有一個小問題,就是在.Net應用程序中傳遞了幾個SQL Server Like
查詢(我無法控制),並且我需要轉義一些字符以使它們成為數據庫的文字。
例如,假設我要查詢的字段看起來像:
This_is [a] long_text field with [literal] characters in it
我的查詢看起來像這樣:
SELECT * FROM [MyTable] where [MyField] Like 'This_% [literal]%'
現在,這應該獲取該數據,挑戰在於SQL Server不會將_
和[
字符視為文字字符,因此我必須將查詢更新為:
SELECT * FROM [MyTable] where [MyField] Like 'This[_]% [[]literal]%'
然后工作。
因此,我的問題是,我想編寫一個使用RegEx來查找語句的Like
部分然后替換字符的VB.Net函數。
類似於以下內容:
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
我知道我提供的信息確實很糟糕,我知道我想要什么,只是無法弄清楚如何使用RegEx做到這一點。
另外,如果有更聰明的方法可以對SQL Server Like
語句執行此操作, 請也讓我知道!!!
謝謝!!
看到該C#
標記后,我認為您可以在C#中給出答案。
string input = "This_is [a] long_text field with [literal] characters in it";
var output = Regex.Replace(input, @"[_\[]","[$0]");
編輯
string input = "SELECT * FROM [MyTable] where [MyField] Like 'This_% [literal]'";
var output = Regex.Replace(input, @"(?<=Like[ ]*\'.+?)[_\[]", "[$0]");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.