.NET中的字符串标记

jul*_*lio 6 .net c# vb.net

我正在用.NET编写一个应用程序,它将根据一些输入生成随机文本.所以,如果我有文字,"I love your {lovely|nice|great} dress"我想随机选择lovely/nice/great并在文本中使用它.欢迎使用C#或VB.NET中的任何建议.

Mar*_*ers 8

您可以使用正则表达式来替换每个{...}.该Regex.Replace函数可以采用a MatchEvaluator来执行从选择中选择随机值的逻辑:

Random random = new Random();
string s = "I love your {lovely|nice|great} dress";
s = Regex.Replace(s, @"\{(.*?)\}", match => {
    string[] options = match.Groups[1].Value.Split('|');
    int index = random.Next(options.Length);
    return options[index];
});
Console.WriteLine(s);
Run Code Online (Sandbox Code Playgroud)

示例输出:

I love your lovely dress

更新:使用.NET Reflector自动转换为VB.NET :

Dim random As New Random
Dim s As String = "I love your {lovely|nice|great} dress"
s = Regex.Replace(s, "\{(.*?)\}", Function (ByVal match As Match) 
    Dim options As String() = match.Groups.Item(1).Value.Split(New Char() { "|"c })
    Dim index As Integer = random.Next(options.Length)
    Return options(index)
End Function)
Run Code Online (Sandbox Code Playgroud)