views:

245

answers:

4

Is it possible to return a string between 2 strings, using regex? For example, if I have this string:

string = "this is a :::test??? string";

Can I write a function to return the word "test" using a regex?

Edit: Sorry, I'm using C#

A: 

Yes, in your regex you can supply the before/after "context" surrounding what you want to match, then use a capture group to return the item you're interested in.

Jim Lewis
+7  A: 

Since you don't mention a language, some C#:

    string input = "this is a :::test??? string";
    Match match = Regex.Match(input, @":::(\w*)\?\?\?");
    if (match.Success)
    {
        Console.WriteLine(match.Groups[1].Value);
    }

(the exact regex patten would depend on what you consider a match... one word? anything? etc...)

Marc Gravell
A: 

if ::: and ??? are your delimeters you could use a regex like:

:::(.*)\?\?\?

And the part in the middle will be returned as the captured group from the match.

Gabriel Hurley
+2  A: 

Since you forgot to indicate a language, I'll answer in Scala:

def findBetween(s: String, p1: String, p2: String) = (
  ("\\Q"+p1+"\\E(.*?)\\Q"+p2+"\\E").r 
  findFirstMatchIn s 
  map (_ group 1) 
  getOrElse ""
)

Example:

scala> val string = "this is a :::test??? string";
string: java.lang.String = this is a :::test??? string

scala>     def findBetween(s: String, p1: String, p2: String) =
     |       ("\\Q"+p1+"\\E(.*?)\\Q"+p2+"\\E").r findFirstMatchIn s map (_ group 1) getOrElse ""
findBetween: (s: String,p1: String,p2: String)String

scala> findBetween(string, ":::", "???")
res1: String = test
Daniel
Well, too late for the C# information. By the way, \Q and \E won't work for .Net languages, according to my reference, so converting this probably won't work.
Daniel