tags:

views:

68

answers:

4

as opposed to regex:'foo.+bar'

+5  A: 

Use a group:

foo(.+?)bar

Then you will be able to refer to the group as $1 or \1, depending on the language and what you are doing with it.

As always, let me recommend Regular-Expressions.info for learning all about regexes.

Michael Myers
thank you! -marienbad
marienbad
Not sure if not hungry notation (.*?) is available in all regex implementations.
lollinus
+1  A: 

Just use:

/foo(.+)bar/
hobodave
A: 

You can use:

foo(.+?)bar

or

foo(.*?)bar

The 2nd one will work even when there is nothing between foo and bar

codaddict
+2  A: 

An alternative would be to use lookaround if the regex flavor you're using (which you didn't specify) supports it. .NET, Python do, Ruby and JavaScript don't (fully), for example:

(?<=foo).+(?=bar)

matches any number of characters if they are preceded by foo and followed by bar.

Tim Pietzcker
perl and PHPs preg_ functions also support this.
Michael Speer
Yes, and I also forgot Java.
Tim Pietzcker