tags:

views:

173

answers:

4

I have a string like following:

CREATE GLOBAL TEMPORARY TABLE some_temp_table_name

OR

CREATE GLOBAL TEMPORARY TABLE some_temp_table_name something else

with the regex I want to strip out whatever is in bold letters.

I have the following regex

([a-z].*[\s]*)

what should I change in the regex?

+1  A: 

Try this:

([A-Z\s]+)[a-z_]+\s?([a-z\s]+)

In Groovy you would do something like this:

String clean 
    = yourString.replaceAll("([A-Z\s]+)[a-z_]+\s?([a-z\s]+)", "$1$2");
Andrew Hare
thanks. that works. but not for first sentence where there is no space after the word I wish to fetch. will changing your answer to ([a-z_]+)\s be alright for that requirement?
Omnipresent
My mistake - my initial answer was wrong. Please see my update.
Andrew Hare
wow hmm your new regex selects the whole string. rather than just the word i wish for..
Omnipresent
Yes it does match the whole string but the two capture groups capture the text you want to _keep_. You need to replace with `\1\2` to remove the text in the middle you don't need. If you let me know what language you are using I can help you with the code that will do the replacement.
Andrew Hare
The Groovy code doesn't work for me, complains about an "Unexpected char '\'".
John Wagenleitner
should be: String clean = yourString.replaceAll("([A-Z\s]+)[a-z_]+\s?([a-z\s]+)", '$1$2');because in groovy strings the values are outputted this way: "${somvar}"
Omnipresent
A: 

try? :

([a-zA-Z\s]+TABLE)\s\b[a-zA-Z_]+\b(.*)
Nona Urbiz
Unfortunately this doesn't seem to work.
Andrew Hare
A: 

If my goal would be to extract lowcase parts I'd do the following in ruby:

'CREATE GLOBAL TEMPORARY TABLE some_temp_table_name '.gsub(/[A-Z]/,'').gsub(/[\s]{2,}/, ' ').strip
dimus
+1  A: 

Based on the 2 cases you provided, the following should work in Groovy:

def s1 = "CREATE GLOBAL TEMPORARY TABLE some_temp_table_name"
def s2 = "CREATE GLOBAL TEMPORARY TABLE some_temp_table_name something else"

def t1 = s1 =~ /CREATE GLOBAL TEMPORARY TABLE (\w+)/ 
def t2 = s2 =~ /CREATE GLOBAL TEMPORARY TABLE (\w+)/ 

assert "some_temp_table_name" == t1[0][1]
assert "some_temp_table_name" == t2[0][1]
John Wagenleitner