更改字符串的输出格式

本文关键字:输出 格式 字符串 | 更新日期: 2023-09-27 17:50:10

我有一个字符串

string str = "a_b_c_ _ _abc_ _ _ _abcd";

现在,str必须转换为以下格式的字符串:

[a][b][c][_ _abc][_ _ _abcd]

如何做到这一点?

更改字符串的输出格式

有点快,但你应该明白。

public static void Main(string[] args) 
{
    Regex regex = new Regex("(([_ ]*[a-z]+)_ ?)+([_ ]*[a-z]+)");
    string str = "a_b_c_ _ _abc_ _ _ _abcd";
    Match match = regex.Match(str);
    // 2 - because of specific regex construction
    for (int i = 2; i < match.Groups.Count; i++) {
        foreach (Capture capture in match.Groups[i].Captures)
            Console.Write("[{0}]", capture.Value);
    }
    Console.ReadLine();
}
https://ideone.com/m3Vhci

stdout
[a][b][c][_ _abc][_ _ _abcd]

另一种说法:

string res = "[" + Regex.Replace(str, @"([^_'s])_'s*", "$1][") + "]";