Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex return value between two values?

Tags:

string

c#

regex

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#

like image 491
Kris B Avatar asked Feb 23 '26 11:02

Kris B


2 Answers

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

like image 74
Marc Gravell Avatar answered Feb 25 '26 01:02

Marc Gravell


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
like image 37
Daniel C. Sobral Avatar answered Feb 25 '26 00:02

Daniel C. Sobral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!