对,说我有{i|we|my friends} are {just|about} to go {walmart|asda|best buy}
这样的字符串我希望能够随机选择{}
中|
所分隔的任何单词{}
这是我所拥有的远,它只适用于一个{}
我需要它来处理多个Function UnspinWork(ByVal SpunWords As String) As String
Dim upperBound As Integer
Dim Random As New Random()
Dim ChosenSpunString As String
SpunWords = Replace(SpunWords, "{" & "}", "")
upperBound = Split(SpunWords, "|").Count
ChosenSpunString = Split(SpunWords, "|")(Random.Next(0, upperBound))
Return ChosenSpunString
End Function
的句子。
{{1}}
谢谢
答案 0 :(得分:0)
使用正则表达式查找所有{}部分。然后使用Regex.Replace方法,使用MatchEvaluator能够指定替换内容。 在此MatchEvaluator中,您可以添加随机选择的逻辑。
在c#中(抱歉,不习惯VB)你可以这样做:
class SpunWords
{
static Random rnd = new Random();
static void Main()
{
var source = "{i|we|my friends} are {just|about} to go {walmart|asda|best buy}";
var pattern = @"\{(?<values>[^\}]*)\}";
var result = Regex.Replace(
source,
pattern,
(m) => Rand(m.Groups["values"].Value)
);
Console.WriteLine(result);
Console.ReadLine();
}
private static string Rand(string value)
{
var parts = value.Split('|');
return parts[rnd.Next(parts.Length)];
}
}
答案 1 :(得分:0)
我只是将史蒂夫b从c#转换为vb.net(幸运的是我知道c#)
Class SpunWords
Shared rnd As New Random()
Private Shared Sub Main()
Dim source = "{i|we|my friends} are {just|about} to go {walmart|asda|best buy}"
Dim pattern = "\{(?<values>[^\}]*)\}"
Dim result = Regex.Replace(source, pattern, Function(m) Rand(m.Groups("values").Value))
Console.WriteLine(result)
Console.ReadLine()
End Sub
Private Shared Function Rand(value As String) As String
Dim parts = value.Split("|"C)
Return parts(rnd.[Next](parts.Length))
End Function
End Class