Kris B
Kris B

Reputation: 3578

Regex return value between two values?

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#

Upvotes: 2

Views: 1382

Answers (4)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297305

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

Upvotes: 2

Gabriel Hurley
Gabriel Hurley

Reputation: 40082

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.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064254

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...)

Upvotes: 7

Jim Lewis
Jim Lewis

Reputation: 45145

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.

Upvotes: 0

Related Questions