tags:

views:

66

answers:

2

I'd like to have one regular expression to find all curly brackets and replace them with other strings.

For example, I want to replace "{foo}" with "FOO" and "{bar}" with "BAR" and "{}" with "EMPTY". If the input is "abc {foo} def {bar} {}", then the output is "abc FOO def BAR EMPTY".

Nested brackets or un-coupled brackets are not allowed. If character "{" or "}" is necessary. It should be doubled. So, "{{ def }}" is just "{ def }".

Other string in {} is not allowed. Say, I just want "{foo}" and "{bar}". So, "abc {xyz} def" should be recognized as invalid input.

+3  A: 

If you have negative lookbehinds/lookaheads available:

(?<!{){([a-z]+)}(?!})

and replace with the value of the matching group.

The ([a-z]+) matches your contained character string, the (?<!{) makes sure there isn't a second { before your {, and the (?!}) makes sure there isn't a second } after your }.

If you don't have lookbehinds/lookaheads, then

(?^|[^{]){([a-z]+)}(?$|[^})
Amber
A: 

I would first go and replace {} with EMPTY without using a regular expression.

Then use

(?<!{){(foo|bar)}(?!})

to match {foo} or {bar} but not {} or {{anything}} or {anything}

Backreference no. 1 contains the matched text.

So a code snippet could look like

Regex matches = new Regex(@"(?<!\{)\{(foo|bar)\}(?!\})", RegexOptions.IgnoreCase);
resultString = matches.Replace(subjectString, "$1".ToUpper());

(I hope that calling ToUpper() on a string works; I don't know C#, so please correct me if I'm wrong)

Tim Pietzcker
I'm not too familiar with C# myself, but I'm almost certain that first the string literal `"$1"` gets capitalized (and nothing gets changed) and after that operation, it is used as a regex-replacement string.
Bart Kiers