2

I want to get text between two strings. For this, I have tried the below code.

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;

Output: SELECT \"NORTHWIND\".\"CUSTOMER_DETAILS_NORTHWIND\".\"CUSTOMER_ID\" FROM

But I expected result without SELECT and FROM keyword.

Expected Output: \"NORTHWIND\".\"CUSTOMER_DETAILS_NORTHWIND\".\"CUSTOMER_ID\"

Can anyone suggest me how to achieve this?

Kavitha M
  • 263
  • 1
  • 7
  • 23

3 Answers3

5
var match = Regex.Match(s, @"(?i)SELECT\s+(.+?)\s+FROM");
if (match.Success)  {
    Console.WriteLine(match.Groups[1].Value);
}
JohnyL
  • 6,894
  • 3
  • 22
  • 41
  • I suggest `(.+?)` - get as few letters as possible in case of `select 123 from select 456 from mytable`; another suggestion is using *case insensitive* regular expression option – Dmitry Bychenko Dec 27 '17 at 08:58
  • @DmitryBychenko I added case-insensitive search. – JohnyL Dec 27 '17 at 09:00
  • imagine, that you have `"select myField from MyTable, (select otherField from other table) ..."` query, it seems that want `myField` match only, not `myField from MyTable, (select otherField` match; that's why it's reasonable to obtain as few letter as possible: `(.+?)` – Dmitry Bychenko Dec 27 '17 at 09:01
  • It's easy to find out a *counter example* (*regular expression* is not a *parser*), say `select /*select 1 from dual*/ myField as "from", myOther from MyTable`; however, the *regular expression* does its work as it can, +1 – Dmitry Bychenko Dec 27 '17 at 09:18
-1

You can do it without RegEx too.

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);
}

Test:

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));

}

Output:

"NORTHWIND"."CUSTOMER_DETAILS_NORTHWIND"."CUSTOMER_ID"
Rickless
  • 1,377
  • 3
  • 17
  • 36
-2

Here you go:

  "SELECT\s+\K\\".*(?=\sFROM)

no need for capture groups, just take the regex match (you can also remove the "SELECT\s+ (it's just an extra verification)

tomersss2
  • 135
  • 12