格式字符串破折号破折号、字符串、格式

2023-09-03 16:52:36 作者:没了皇冠照样是女王

我有一个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);
 
oracle这个sql怎么不对,报 文字格式与字符串不匹配

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");