简体   繁体   English

格式化字符串

[英]Format A String

Well, 好,

I just can't format the following string: 我只是无法格式化以下字符串:

string oldFormat = "949123U0456789";
oldFormat = string.Format(@"{0: ###.###-##-###.###}",oldFormat);

the result should be: 949.123-U0-456.789 结果应该是:949.123-U0-456.789

Does anyone have a better way to format this string? 有谁有更好的方式格式化此字符串?

You can use Insert : 您可以使用Insert

"949123U0456789".Insert(11, ".").Insert(8, "-").Insert(6, "-").Insert(3, ".")

Note that I am inserting from the end, to avoid the addition of the inserted string from affecting the index. 请注意,我从头开始插入,以避免插入的字符串的添加影响索引。

The format string you have used is meant for numeric types - a string is not a numeric types (and when passing in a string to string.Format , it will simply be returned, as it already is a string). 您使用的格式字符串适用于数字类型-字符串不是数字类型(并且在将字符串传递给string.Format ,由于它已经是字符串,因此将简单地返回)。

There are other approaches, as can be seen in Format string with dashes : 还有其他方法,如带破折号的格式字符串中所示

Using regex: 使用正则表达式:

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

Or with Substring. 或带子串。

Regex can solve the problem of formatting when there is a mix of letters and numbers. 当字母和数字混合在一起时,正则表达式可以解决格式问题。

        using System.Text.RegularExpressions;

        string pattern = @"([a-z0-9A-Z]{3})([a-z0-9A-Z]{3})
                    ([a-z0-9A-Z]{2})([a-z0-9A-Z]{3})([a-z0-9A-Z]{3})"
        string oldFormat = "949123U0456789";
        string newFormat = Regex.Replace(oldFormat, pattern, 
                    "$1.$2-$3-$4.$5");

I love regular expressions :D, they have the added benefit of allowing you to check the syntax of the code, if it has to follow a certain convention (ie perform validation). 我喜欢正则表达式:D,如果必须遵守某种约定(即执行验证),它们还有其他好处,即允许您检查代码的语法。

In order to perform validation, you can use: 为了执行验证,您可以使用:

        Regex.IsMatch(oldFormat, 
                    @"([a-z0-9A-Z]{3})([a-z0-9A-Z]{3})
                    ([a-z0-9A-Z]{2})([a-z0-9A-Z]{3})
                    ([a-z0-9A-Z]{3})")
string s="949123U0456789";

Regex r=new Regex(@"(\w{3})(\w{3})(\w{2})(\w{3})(\w{3})");
Console.WriteLine(r.Replace(s,"$1.$2-$3-$4.$5"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM