Quantcast
Channel: Regex Match all characters between two strings - Stack Overflow
Viewing all articles
Browse latest Browse all 19

Answer by The fourth bird for Regex Match all characters between two strings

$
0
0

In case of JavaScript you can use [^] to match any character including newlines.

Using the /s flag with a dot . to match any character also works, but is applied to the whole pattern and JavaScript does not support inline modifiers to turn on/off the flag.

To match as least as possible characters, you can make the quantifier non greedy by appending a question mark, and use a capture group to extract the part in between.

This is([^]*?)sentence

See a regex101 demo.

As a side note, to not match partial words you can use word boundaries like \bThis and sentence\b

const s = "This is just\na simple sentence";const regex = /This is([^]*?)sentence/;const m = s.match(regex);if (m) {  console.log(m[1]);}

The lookaround variant in JavaScript is (?<=This is)[^]*?(?=sentence) and you could check Lookbehind in JS regular expressions for the support.

Also see Important Notes About Lookbehind.

const s = "This is just\na simple sentence";const regex = /(?<=This is)[^]*?(?=sentence)/;const m = s.match(regex);if (m) {  console.log(m[0]);}

Viewing all articles
Browse latest Browse all 19

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>