views:

486

answers:

4

I want to extract

FROM codes WHERE FieldName='ContactMethod' and IsNull(Deactived,'') != 'T'

from

SELECT FieldDescription,FieldValue FROM codes WHERE FieldName='ContactMethod'
   and IsNull(Deactived,'') != 'T' order by fielddescription

using a regular expression. I have a regex like this:

\FROM.*\order

which extracts

FROM codes WHERE FieldName='ContactMethod' and IsNull(Deactived,'') != 'T' order

Also, how can I get rid of the capitalization?

Thanks

+1  A: 

The trick here would probably be to capture the part you actually want with parens:

(FROM.*) order

This would greedily match until the last order, if you want only until the first occurrence, match lazily:

(FROM.*?) order
Fabian Steeg
This one works but I don't want the word "Order" i want everything starting from the word "FROM" till the word "order" excluding the word "Order" also i want it case insensitive.
Mithil Deshmukh
isn't that what the (parentheses) are for?
Chris Farmer
It still gives me " FROM codes WHERE FieldName='ContactMethod' and IsNull(Deactived,'') != 'T' order"
Mithil Deshmukh
The first match (the stuff in brackets) will be the part without order. Read up about RegEx matches.
cdmckay
To not have order show up in the match, do this "(FROM.*)(?=order)"
Jeff Moser
Awesome...this works...Thanks Jeff
Mithil Deshmukh
Thanks all who took time to answer my question!
Mithil Deshmukh
FYI: You can use the expression that Fabian gives and say Regex.Match("(FROM.*) order").Groups[1].Value
Jeff Moser
I'd also recommend using ` (FROM .*) ORDER BY ` (note spaces around FROM and inclusion of "BY ") for a little extra robustness, in case the table's name includes "from" or the FROM clause contains " order".
Ben Blank
A: 

If it comes down to it you can ignore capitalization by doing (F|f)(R|r)(O|o)(M|m).

Albert
yup..that solves the case sensitive issue. I am still getting the word "Order" which i don't want. I am using (from|FROM.*)order|ORDER
Mithil Deshmukh
Nearly all regex flavors support a case-insensitivity flag.
Ben Blank
+1  A: 

Expanding on Fabian Steeg's answer

 Dim regex As Regex = New Regex( _
          "(FROM.*?) ORDER", _
        RegexOptions.IgnoreCase _
        Or RegexOptions.CultureInvariant _
        Or RegexOptions.IgnorePatternWhitespace _
        Or RegexOptions.Compiled _
        )

    Dim ms As MatchCollection = regex.Matches(InputText)

where InputText is of course your SQL query string.

ms(1) should hold the parentheses match

Michael G
A: 

Interactive tools like RegexBuddy ($40) or The Regex Coach (free) would really help you to design and debug regular expressions for most platforms.

Jonathan Webb