0

How can I simply check if a string contains {x} (x can be any number)?

I guess there is some simple RegEx to do this.

"This string contains {0} a placeholder".HasPlaceholder == true

and

"This string contains no placeholder".HasPlaceholder == false
KingKerosin
  • 3,639
  • 4
  • 38
  • 77
  • Really, just a number inside `{...}`? Did you really have any problem with such a basic regex? I assumed you need to match any `string.Format` placeholders at the beginning, but now it seems just a dupe of [Learning Regular Expressions](http://stackoverflow.com/a/2759417/3832970). – Wiktor Stribiżew Apr 15 '16 at 09:13
  • Does this string contain a placeholder? `"A {{0}} B"`? – Lasse V. Karlsen Apr 15 '16 at 10:20

1 Answers1

5

You can write a simple extension and use a regex:

public static class StringExtensions
{
    public static bool HasPlaceholder(this string s)
    {
        return Regex.IsMatch(s, "{\\d+}");
    }
}

This regex works only for the placeholders you specified (containing only a number).

For a full placeholder you would need something like "{\\d+(,-?\\d+)?(:[A-Z]\\d*)?}". But this still needs refinement. See "Standard Numeric Format Strings" for a full list of valid symbols.

You can use this extension like this:

string s = "This string contains {0} a placeholder";
if (s.HasPlaceholder())
    Console.WriteLine("Contains placeholders");
René Vogt
  • 43,056
  • 14
  • 77
  • 99
  • See [*Standard Numeric Format Strings*](https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx) for the possible formats that the pattern should cover to answer the question. – Wiktor Stribiżew Apr 15 '16 at 09:05
  • 2
    @WiktorStribiżew included your link, thanks. But the question explicitly asks for `{anynumber}`, not for a regex valid for all possibilities – René Vogt Apr 15 '16 at 09:09
  • If it is, then the question must be closed as a dupe of [Learning Regular Expressions](http://stackoverflow.com/a/2759417/3832970). – Wiktor Stribiżew Apr 15 '16 at 09:14