1

I want to match all the words in a string which have pattern like {{word}}

For Example:

This {{is}} a test {{String}}. Should match {{is}} and {{String}}

I was using /{{(.*?)}}/g which gives correct result for above case but fails when I have string something like

This {{is{{is}}}} a test String

Output Should be: {{is{{is}}}} but it is returning {{is{{is}}

Prashant Agrawal
  • 660
  • 9
  • 24
  • 1
    This is an issue of balancing groups which isn't easy to do with Javascript's flavor of regex. See, for example, [this](http://stackoverflow.com/questions/20726770/how-to-match-balanced-delimiters-in-javascript-regex) – Matt Burland Mar 30 '17 at 17:42
  • @9000 i thought js regex didn't support lookbehind. does it? – Rico Kahler Mar 30 '17 at 17:52
  • @Rico: Well, yes, I was wrong, removed my comment. – 9000 Mar 30 '17 at 17:52

1 Answers1

4

One possible way is this.

{{[\w{}]+}}
Chuancong Gao
  • 654
  • 5
  • 7
  • You are making an assumption about what can be inside the braces (i.e. only word characters) – Matt Burland Mar 30 '17 at 17:43
  • If we do not have this assumption, then regex can not be used here. Because regex in JavaScript does not support recursive. https://stackoverflow.com/questions/4414339/recursive-matching-with-regular-expressions-in-javascript – Chuancong Gao Mar 30 '17 at 17:44
  • You could also use `\S` in place of `\w{}`, granted the `word` doesn't contain any spaces. This would allow for numbers and other symbols to be used. – J. Titus Mar 30 '17 at 17:53
  • `\w` allows digits. I agree we can use `\S` instead if we need to support other symbols. – Chuancong Gao Mar 30 '17 at 17:57