开发者

Replace {tag} with a value or completely remove {any-tag}

I've designed a multilingual web site and some values in database have a tag which will be replaced with it's language value, remove tags brackets ( in case {} ) or removed completely.

There are two cases:

Remove brackets:

value {mm} >> value mm

Remove completely:

开发者_Python百科value {mm} >> value

Also {tag} could be any length and can contain -

Can anybody help me with regex?


Here is some code you might find useful. For many many more options, see Regular-expressions.info.

All code Using System.Text.RegularExpressions;


Remove all occurrences of {mm} (and only mm):

Regex.Replace(myString, "{mm}", String.Empty, RegexOptions.None);

Replace all occurrences of {mm} (and only mm) with mm:

Regex.Replace(myString, "{mm}", "mm", RegexOptions.None);

Remove all occurrences of {any-characters}:

Regex.Replace(myString, @"{[\-a-z]*}", String.Empty, RegexOptions.IgnoreCase);

Replace all occurrences of {any-characters} with any-characters:

Regex.Replace(myString, @"{(?<tag>[\-a-z]*)}", "${tag}", RegexOptions.IgnoreCase);


.Net already provides a similar functionality using String.Format.

string.Format("value {0}", ""); // returns "value "
string.Format("value {0}", "some value"); // returns "value some value"

You can do more advanced things with this method, such as specifying formatting for numbers:

string.Format(new CultureInfo("en-US"), "value {0:N}", 10000); // returns 10,000.00
string.Format(new CultureInfo("es-ES"), "value {0:N}", 10000); // returns 10.000,00

The two downsides to this method:

  1. No case for removing the brackets.
  2. Can't name your placeholders. You have to use ordinal placeholders. {0}, {1}...{n}.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜