1

I'm trying to match a part of a string between two different tokens. They might be multiple occurrences of the tokens in a string.

Sample text (tokens are italic, text to match is bold):

This is [begin-match] a sample text [end-match] with some [begin-match] tokens and normal [end-match] text.

I have the following regex, which would work if the tokens were { and }:

/{([^}]+)}/g

I can't get this to work the [begin-match] and [end-match] tokens. It seems that the lack of negative lookbehind in Javascript is a big loss.

I can't figure out how to substitute the { and } for the tokens [begin-match] and [end-match]. How can I match on those?

Roemer
  • 3,526
  • 1
  • 15
  • 31
  • You probably also need to know [What special characters must be escaped in regular expressions?](http://stackoverflow.com/questions/399078/what-special-characters-must-be-escaped-in-regular-expressions) – HamZa May 04 '15 at 10:19

2 Answers2

4

/x(.*?)y/g where x is the beginning token and y the ending token.

This RegEx means: match anything (.), any number of times (*), as few times as possible (?).

A direct example from your question would be:

/\[begin-match\](.*?)\[end-match\]/g

The sample text is now in the first capturing group.

Sebastian Simon
  • 16,564
  • 7
  • 51
  • 69
2
\[begin-match\]((?:(?!\[end-match\]).)*)\[end-match\]

You can try this.See demo.

https://regex101.com/r/uE3cC4/23

vks
  • 65,133
  • 10
  • 87
  • 119