joerage
joerage

Reputation: 4923

Regular Expression to stop after first find

if I have the following text:

some text
CREATE DATABASE [$(DatabaseName)]
This can be any text
GO

other text
GO

more text

I would like to only match

CREATE DATABASE [$(DatabaseName)]  
any text that is here
GO

using Regular Expression. What I have tried so far fails and gives me everything up to the last GO. I would like to stop after finding the first occurence of GO.

This is what I tried:

CREATE DATABASE[^<>]*^(GO)+?

I understand why it does not work, but don't know how to fix it. Thanks a lot.

Upvotes: 1

Views: 401

Answers (5)

joerage
joerage

Reputation: 4923

I found how to do it:

CREATE DATABASE+([\s\S]*?)+GO

or still shorter

CREATE DATABASE[\s\S]*?GO

Upvotes: 0

PandaWood
PandaWood

Reputation: 8343

As I understand it, this works for me (where dot matches new line is set, if necessary)

CREATE DATABASE.*?GO

See it tested at rubular.com with this permalink I created for it: http://rubular.com/r/2KsBrnSGhC

Upvotes: 1

Alex7575
Alex7575

Reputation: 65

I'm terrible with regex, so if you're in a .Net environment, try using this great addin from MS:

http://visualstudiogallery.msdn.microsoft.com/en-us/55c24bf1-2636-4f94-831d-28db8505ce00

Upvotes: 0

Chris B. Behrens
Chris B. Behrens

Reputation: 6295

This will do it:

CREATE DATABASE \[(.+?)\]

Upvotes: 1

Jahan Zinedine
Jahan Zinedine

Reputation: 14874

Append a ? to your regex to make it non greedy

http://www.lbsharp.com/wordpress/index.php/2007/02/19/net-regular-expressions/

Upvotes: 2

Related Questions