-1

I have a text template that has text variables wrapped with {{ and }}.

I need a regular expression to gives me all the matches that "Include {{ and }}".

For example if I have {{FirstName}} in my text I want to get {{FirstName}} back as a match to be able to replace it with the actual variable.

I already found a regular expression that probably gives me what is INSIDE { and } but I don't know how can I modify it to return what I want.

/\{([^)]+)\}/
Pouyan
  • 2,849
  • 8
  • 33
  • 39
  • Does C# have a function similar to [`java.lang.String#replace`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replace-java.lang.CharSequence-java.lang.CharSequence-)? – The SE I loved is dead Jul 22 '16 at 17:16

2 Answers2

2

This pattern should do the trick:

string str = "{{FirstName}} {{LastName}}";

Regex rgx = new Regex("{{.*?}}");

foreach (var match in rgx.Matches(str))
{
    // {{FirstName}}
    // {{LastName}}
}
Zein Makki
  • 29,485
  • 6
  • 52
  • 63
  • 1
    A better alternative is `Regex rgx = new Regex("{{.*?}}");`, and if the string in between braces is huge, you'd better consider unrolling it as `Regex rgx = new Regex("{{[^}]*(?:}(?!})[^}]*)*}}");` – Wiktor Stribiżew Jul 22 '16 at 19:29
0

Maybe:

alert(/^\{{2}[\w|\s]+\}{2}$/.test('{{FirstName}}'))

^: In the beginning.

$: In the end.

\{{2}: Character { 2 times.

[\w|\s]+: Alphabet characters or whitespace 1 or more times.

\}{2}: Character } 2 times.

UPDATE:

alert(/(^\{{2})?[\w|\s]+(\}{2})?$/.test('FirstName'))
Tân
  • 1
  • 15
  • 56
  • 102