开发者

Function to match text in {word1|word2} format

Right say i have a string such as {i|we|my friends} are {just|about} to go {walmart|asda|best buy} i would like to be able to randomly choose any of the words within the {} seperated by the | here is what i have so far and it only works for one {} i need it to work for sentences with multiple {}.

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, uppe开发者_如何学JAVArBound))
    Return ChosenSpunString
End Function

Thanks


Use a regex to find all {} parts. Then use the Regex.Replace method, using a MatchEvaluator to be able to specify what is replacement. In this MatchEvaluator, you can add the logic for choosing randomly.

In c# (sorry, not used to VB) you can do :

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)];
    }
}


I am simply converting steve b's from c# to vb.net (luckily i know 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜