簡體   English   中英

C#正則表達式:匹配以x開頭,以y結尾的字符串,不包括結尾部分,並匹配模式的最后一次出現

[英]C# regex: match a string starting with x and ending with y, not including the ending part & match the last occurence of a pattern

我有一個這樣的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 ([testCountry].[Division] <> '' and [testCountry].[Division] is not null)結尾處的Where子句WHERE ([testCountry].[Division] <> '' and [testCountry].[Division] is not null)

我該如何組成正則表達式?

我已經嘗試過這樣的事情:

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

但是它將刪除其他位置的所有WHERE ,然后刪除ORDER BY 另外如何更簡潔地編寫正則表達式?

謝謝!

我知道這不是您所要求的正則表達式解決方案,但這是一個解決方案。

var sql = "WHERE THIS = THIS WHERE this = that ";

var index = sql.LastIndexOf("WHERE");

var sqlnew = sql.Substring(0, index);

您可以使用上面的命令刪除最后一個WHERE語句。 然后,在末尾附加where語句要容易得多。

如果您還可以獲取最后的WHERE語句並進行正則表達式,則可以輕松得多。

   var whereStatement = sql.Substring(index, sql.length);

然后得到你想要的例子。

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

如果您匹配其他WHERE ,則不必擔心替換它們。 嘗試

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

根據貪婪匹配的性質,這將確保僅最后一個WHERE子句被匹配。

作為記錄,我更喜歡約書亞的方法 盡可能避免使用正則表達式,無論您之后的任何人(包括您將來的自己)都將不勝感激。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM