-3

I have written following regex for extracting sql statement from string

((?:SELECT|INSERT)[\s\S]*?\;)

It's working fine but it's capturing last quotes and semicolon while I want string between quotes? Any help will be appreciated

Output Snapshot

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
muski
  • 35
  • 4
  • Is that suppose to be C# code you're running the regex on? If so it seems to be missing plus signs for concatenating those strings together. – juharr Feb 22 '17 at 15:18

2 Answers2

1

You can use lookahead to avoid that.

((?:SELECT|INSERT)[\s\S]*?)(?=";)

Using this positive lookahead (?=";) it makes sure that your regex ends before that ";, and it will not capture in your group.

Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85
0

Regexp:

(?:SELECT|INSERT)[\s\S]*?(?=\"|\;)

Input:

"SELECT DISTINCT "
"SELECT DISTINCT "
"SELECT DISTINCT "
"SELECT DISTINCT ";

Output: (Example...)

SELECT DISTINCT
SELECT DISTINCT
SELECT DISTINCT
SELECT DISTINCT

C# Code:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(?:SELECT|INSERT)[\s\S]*?(?=\""|\;)";
        string input = @"""SELECT DISTINCT ""
""SELECT DISTINCT ""
""SELECT DISTINCT ""
""SELECT DISTINCT "";";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

See: https://regex101.com/r/rzBTpo/2