Ian Ringrose
Ian Ringrose

Reputation: 51917

How to validate format string

We have lots of strings in our resource files that contains format .e.g

“{0} has moved to {1}”

These strings are passed to String.Format() by the applications, sometimes the translators mess up the “formatting markers” Therefore I wish to find/write a tool that checks that all strings in the resource file has a valid format.

I know for each key the numbers of args that are passed to String.Format so that can feed into the validations as well.

So apart from checking that the “{“ match the “}” is there a easy way to find most errors in the format strings?

(I am using .NET, this checking will of course be done as part of the build process)

Upvotes: 0

Views: 939

Answers (3)

Ian Ringrose
Ian Ringrose

Reputation: 51917

I have come up with a simple solution that gives a reasonable result, I know the number of argument to the format statement but not the type of the arguments. However most arguments are strings.

So

if (numberOfArguments == 3)
{
  try
  {
    String.Format(theTranslatorString, "", "", "")
  }
  catch
  {
     // tell the translator there is a problem with the string format
  }
}

Of course this would be written without an “if” for each number of arguments in real life.

Upvotes: 1

Myra
Myra

Reputation: 3656

It looks like you validate a string in expression,so you should use Regular Expressions Look at link text

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272297

This sounds like a classic unit-test scenario. Can you drive an automated build/unit-test off the source-code commit trigger for these ? The unit test would simply check that each format string is still parse-able.

Upvotes: 1

Related Questions