[英]Get string between two words using C# regex
我想在兩個字符串之間獲取文本。 為此,我嘗試了以下代碼。
string q = "SELECT \"NORTHWIND\".\"CUSTOMER_DETAILS_NORTHWIND\".\"CUSTOMER_ID\" FROM \"NORTHWIND\".\"CUSTOMER_DETAILS_NORTHWIND\"";
Regex regex = new Regex("SELECT(.*)FROM");
var result = regex.Match(q).Value;
輸出 :SELECT \\“ NORTHWIND \\”。\\“ CUSTOMER_DETAILS_NORTHWIND \\”。\\“ CUSTOMER_ID \\” FROM
但是我期望沒有SELECT和FROM關鍵字的結果。
預期輸出: \\“ NORTHWIND \\”。\\“ CUSTOMER_DETAILS_NORTHWIND \\”。\\“ CUSTOMER_ID \\”
誰能建議我如何實現這一目標?
string input = "SELECT \"NORTHWIND\".\"CUSTOMER_DETAILS_NORTHWIND\".\"CUSTOMER_ID\" FROM \"NORTHWIND\".\"CUSTOMER_DETAILS_NORTHWIND\"";
Regex regex = new Regex("SELECT(.*)FROM");
var result = regex.Match(input);
var output = result.Groups[1].ToString();
var match = Regex.Match(s, @"(?i)SELECT\s+(.+?)\s+FROM");
if (match.Success) {
Console.WriteLine(match.Groups[1].Value);
}
您也可以不使用RegEx
。
public static string GetBetweenTwoWords(string firstWord,string secondWord,string str){
var firstWordIndex = str.IndexOf(firstWord) + firstWord.Length;
var secondWordIndex = str.IndexOf(secondWord);
return str.Substring(firstWordIndex,secondWordIndex - firstWordIndex);
}
測試:
static void Main(string[] args)
{
string q = "SELECT \"NORTHWIND\".\"CUSTOMER_DETAILS_NORTHWIND\".\"CUSTOMER_ID\" FROM \"NORTHWIND\".\"CUSTOMER_DETAILS_NORTHWIND\"";
Console.WriteLine(GetBetweenTwoWords("SELECT","FROM",q));
}
輸出:
"NORTHWIND"."CUSTOMER_DETAILS_NORTHWIND"."CUSTOMER_ID"
干得好:
"SELECT\s+\K\\".*(?=\sFROM)
無需捕獲組,只需進行正則表達式匹配即可(您也可以刪除“ SELECT \\ s +”(這只是額外的驗證)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.