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