格式字符串破折号 [英] Format string with dashes

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

问题描述

我有一个COM pressed字符串值,我是从导入文件中提取。我需要格式化这个成一个包号,格式如下: ## - ## - ## - ### - ### 。因此,因此,字符串410151000640应该成为41-01-51-000-640。我可以用下面的code做到这一点:

 的String.Format({0:##  -  ##  -  ##  -  ###  -  ###},Convert.ToInt64(410151000640));
 

不过,该字符串可能不是所有的数字;它可以有一个或两个字母在那里,因此,换算为int将失败。有没有办法做到这一点的一个字符串,所以每个字符,不管它是一个数字或字母,将适合的格式是否正确?

解决方案

  Regex.Replace(410151000640,@^(。{2})({2})( 。{2})({3})({3})$,$ 1- $ $ 2- 3- 4- $ $ 5);
 

还是略短版

  Regex.Replace(410151000640,@^(..)(..)(..)(...)(...)$,$ 1 -  $ 2- $ 3- $ 4- $ 5);
 

I have a compressed string value I'm extracting from an import file. I need to format this into a parcel number, which is formatted as follows: ##-##-##-###-###. So therefore, the string "410151000640" should become "41-01-51-000-640". I can do this with the following code:

String.Format("{0:##-##-##-###-###}", Convert.ToInt64("410151000640"));

However, The string may not be all numbers; it could have a letter or two in there, and thus the conversion to the int will fail. Is there a way to do this on a string so every character, regardless of if it is a number or letter, will fit into the format correctly?

解决方案

Regex.Replace("410151000640", @"^(.{2})(.{2})(.{2})(.{3})(.{3})$", "$1-$2-$3-$4-$5");

Or the slightly shorter version

Regex.Replace("410151000640", @"^(..)(..)(..)(...)(...)$", "$1-$2-$3-$4-$5");

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

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