我想在两个字符串之间获取文本。为此,我尝试了以下代码。
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 \"来自
但我期望没有SELECT和FROM关键字的结果。
预期输出: \" NORTHWIND \"。\" CUSTOMER_DETAILS_NORTHWIND \"。\" CUSTOMER_ID \"
有谁能建议我如何实现这个目标?
答案 0 :(得分:1)
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();
答案 1 :(得分:1)
var match = Regex.Match(s, @"(?i)SELECT\s+(.+?)\s+FROM");
if (match.Success) {
Console.WriteLine(match.Groups[1].Value);
}
答案 2 :(得分:0)
您也可以在没有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"
答案 3 :(得分:0)
你走了:
"SELECT\s+\K\\".*(?=\sFROM)
不需要捕获组,只需要进行正则表达式匹配 (你也可以删除“SELECT \ s +(它只是一个额外的验证)