How to validate format string

笑着哭i 提交于 2019-12-25 04:30:18

问题


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)


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/1277288/how-to-validate-format-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!