Skip to main content
 首页 » 编程设计

C# 正则表达式 : match a string starting with x and ending with y, 不包括结尾部分 & 匹配模式的最后一次出现

2024年02月05日31pander-it

我有这样一条sql语句,我们需要修改它以供我们自己使用:

SELECT distinct  [testCountry].[Division] as c0 
FROM (....) AS testCountry  
WHERE ([testCountry].[Division] <> '' and [testCountry].[Division] is not null) 
ORDER BY [testCountry].[Division] asc 

(....)部分包含其他sql语句,可能包含关键字SELECT, WHERE, ORDER BY以及。 这里我想删除末尾的Where子句“WHERE ([testCountry].[Division] <> '' and [testCountry].[Division] is not null)”

如何为此编写正则表达式?

我试过这样的东西:

string res = Regex.Replace(originalSql, @"(WHERE[\S\s]*?)(ORDER BY)", "$2"); 

但它会删除所有 WHERE在其他地方紧随其后的是ORDER BY . 另外如何更简洁地编写正则表达式?

谢谢!

请您参考如下方法:

如果你匹配了其他WHERE,那么你就不用担心替换它们了。尝试

string res = Regex.Replace(originalSql, @"(.*)(WHERE[\S\s]*?)(ORDER BY)", "$1$3"); 

根据贪婪匹配的性质,这将确保只匹配最后一个 WHERE 子句。

郑重声明,我喜欢Joshua's approach更好的。尽可能避免使用正则表达式,之后出现的任何人(包括你 future 的自己)都会感激不尽。