解析格式化的字符串 [英] Parsing formatted string

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

问题描述

我正在尝试创建通用的格式化程序/解析器组合。

I am trying to create a generic formatter/parser combination.

示例场景:


  • 我有一个string.Format()的字符串,例如 var format = {0}-{1}

  • 我有一个用于输入的对象(字符串)数组,例如 var arr = new [] { asdf, qwer}

  • 我正在使用格式字符串格式化数组,例如 var res = string.Format(format,arr)

  • I have a string for string.Format(), e.g. var format = "{0}-{1}"
  • I have an array of object (string) for the input, e.g. var arr = new[] { "asdf", "qwer" }
  • I am formatting the array using the format string, e.g. var res = string.Format(format, arr)

我是什么尝试做的是将格式化的字符串恢复为对象(字符串)的数组。类似于(伪代码):

What I am trying to do is to revert back the formatted string back into the array of object (string). Something like (pseudo code):

var arr2 = string.Unformat(format, res)

// when: res = "asdf-qwer"    
// arr2 should be equal to arr

有人有做这样的经历的经验吗?我正在考虑使用正则表达式(修改原始格式字符串,然后将其传递给Regex.Matches以获取数组)并为格式字符串中的每个占位符运行它。这是否可行?或者还有其他更有效的解决方案吗?

Anyone have experience doing something like this? I'm thinking about using regular expressions (modify the original format string, and then pass it to Regex.Matches to get the array) and run it for each placeholder in the format string. Is this feasible or is there any other more efficient solution?

推荐答案

您无法取消格式化,因为信息丢失了。 String.Format 是一种破坏性算法,这意味着您不能(始终)返回。

You can't unformat because information is lost. String.Format is a "destructive" algorithm, which means you can't (always) go back.

创建一个从 string 继承的新类,在其中添加一个跟踪 {0}-{1} { asdf, qwer} ,覆盖 ToString(),并进行一些修改您的代码。

Create a new class inheriting from string, where you add a member that keeps track of the "{0}-{1}" and the { "asdf", "qwer" }, override ToString(), and modify a little your code.

如果变得太棘手,只需创建相同的类,但不要继承 string 并进行修改多一点代码。

If it becomes too tricky, just create the same class, but not inheriting from string and modify a little more your code.

IMO,这是最好的方法。

IMO, that's the best way to do this.

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

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