Reputation: 531
I am trying to find a way to match every character between two strings.
For example, for the given string abc--def--ghi
, I want the regex to match d
, e
, and f
.
I've tried using the following regex (?<=--)(.*)(?=--)
, however this matches all the characters between --
(def
), whereas I need to match every character between --
.
s.match(/--(.*?)--/)[1].split("")
doesn't work as I need to do this without splitting.
Any suggestions?
Upvotes: 1
Views: 825
Reputation: 627400
In JavaScript, using the ECMAScript 2018+ compliant regex engine, you can achieve what you want without additional split step using
/(?<=--(?:(?!--).)*).(?=(?:(?!--).)*--)/gs
/(?<=--[^-]*(?:-(?!-)[^-]*)*).(?=[^-]*(?:-(?!-)[^-]*)*--)/gs
See the regex demo (the second variant is the same regex as the first one, but more efficient as it follows the "unroll-the-loop" principle). Details:
(?<=--(?:(?!--).)*)
- a location immediately preceded by --
and then any one or more (as many as possible) chars, each of which does not start a --
char sequence.
- any single char(?=(?:(?!--).)*--)
- immediately followed by any one or more (as many as possible) chars, each of which does not start a --
char sequence, and then --
.The s
flag enables .
to match any char including line break chars that .
does not match by default.
Upvotes: 2