formatting string in MVC /C#

后端 未结 10 2172
不知归路
不知归路 2021-02-19 03:15

I have a string 731478718861993983 and I want to get this 73-1478-7188-6199-3983 using C#. How can I format it like this ?

Thanks.

10条回答
  •  没有蜡笔的小新
    2021-02-19 03:43

    If you're dealing strictly with a string, you can make a simple Regex.Replace, to capture each group of 4 digits:

    string str = "731478718861993983";
    str = Regex.Replace(str, "(?!^).{4}", "-$0" ,RegexOptions.RightToLeft);
    Console.WriteLine(str);
    

    Note the use of RegexOptions.RightToLeft, to start capturing from the right (so "12345" will be replaced to 1-2345, and not -12345), and the use of (?!^) to avoid adding a dash in the beginning.
    You may want to capture only digits - a possible pattern then may be @"\B\d{4}".

提交回复
热议问题