如何验证格式字符串 [英] How to validate format string

查看:157
本文介绍了如何验证格式字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的资源文件中有很多字符串,它们包含.e.g

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

"{0}已移至{1}"

"{0} has moved to {1}"

这些字符串由应用程序传递给 String.Format(),有时翻译者将格式标记"弄乱了.因此,我希望找到/编写一种工具来检查资源文件具有有效格式.

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.

我知道每个键传递给String.Format的args的数量,以便也可以将其输入验证中.

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?

(我使用的是.NET,这种检查当然会在构建过程中完成)

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

推荐答案

我提出了一个给出合理结果的简单解决方案,我知道format语句的参数个数,但不知道参数的类型.但是,大多数参数都是字符串.

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.

所以

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

当然,对于现实生活中的每个论点,在编写时都不会带有"if".

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

这篇关于如何验证格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆