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