I want to take all of the substrings inside of string which is between given two regex. Couple examples:
My $$name$$ is John, my $$surname$$ is Doe -> should return [name, surname]
My &&name&& is John, my &&surname&& is Doe -> should return again [name, surname]
I have tried couple solutions but non of them works for multiple substring with given dynamic values. How can I do that?
3
Answers
Use this regex :
(?<=$$|&&)(w+)(?=$$|&&)
Explanation :
(?<=r)d
: matches ad
only if is preceded by anr
, butr
will not be part of the overall regex match.d(?=r)
: matches ad
only if is followed byr
, butr
will not be part of the overall regex match.I would use this:
https://regex101.com/r/j4iR9O/2
The idea is to use two patterns (one for
$$
and one for&&
).This can be done with the
|
syntax.Then, I’m using a positive lookbehind
(?<= )
to search for the$$
thatI have to escape with a slash because
$
has a meaning in regular expressions.For the positive lookahead, it’s
(?= )
.In the middle, I want to match any word character or underscores (as it’s a
variable name). This leads to
[w_]+
meaning word char or underscores, atleast once or several times.
Using regular expression groups you can extract the values between a specified delimiter and then capturing a group in between those delimiters.
Works by creating a regex such as
$$(w+)$$
using the specified delimiter.