1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Nested(multi-layered) Spintax script for c# and vb.net

Discussion in 'General Programming Chat' started by Just A Tyler Durden, Sep 12, 2015.

  1. Just A Tyler Durden

    Just A Tyler Durden Regular Member

    Joined:
    Jul 1, 2014
    Messages:
    207
    Likes Received:
    89
    Hey guys, for any bot programmers out there I know this will help a lot of you. Currently I'm trying to get recode this into delphi without any luck but I have been able to shortened the spintax function down to 12 lines of code in vb.net/C#. So here you guys go, a simple function that can spin nested (multi-layered) spintax for example {1|2{a|b}|3{a{1|2}|b{1|2}}}, this function can handle any spintax with as much layers as you want.

    P.S this is not my code I simply shortened down the original one that was 26 lines of code and made it as simple as possible, if anyone can help me convert this into delphi please contact me, message me on here or add me on skype: etfluxproject

    To use it simply call the function with the spintax inside, for example msgbox(spin({1|2{a|b}|3{a{1|2}|b{1|2}}})) this will show a message box with the spun article, enjoy.

    for vb.net
    Code:
     Function Spin(ByVal source As String)
            Dim rand As New Random()
            Dim pattern As String = "\{[^{}]*\}"
            Dim m As Match = Regex.Match(source, pattern)
            While m.Success
                Dim seg As String = source.Substring(m.Index + 1, m.Length - 2)
                Dim choices As String() = seg.Split("|"c)
                source = source.Substring(0, m.Index) + choices(rand.[Next](choices.Length)) + source.Substring(m.Index + m.Length)
                m = Regex.Match(source, pattern)
            End While
            Return source
        End Function
    

    and for C#
    Code:
    public object Spin(string source)
    {
        Random rand = new Random();
        string pattern = "\\{[^{}]*\\}";
        Match m = Regex.Match(source, pattern);
        while (m.Success) {
            string seg = source.Substring(m.Index + 1, m.Length - 2);
            string[] choices = seg.Split('|');
            source = source.Substring(0, m.Index) + choices(rand.Next(choices.Length)) + source.Substring(m.Index + m.Length);
            m = Regex.Match(source, pattern);
        }
        return source;
    }
    
     
    Last edited: Sep 12, 2015
  2. Just A Tyler Durden

    Just A Tyler Durden Regular Member

    Joined:
    Jul 1, 2014
    Messages:
    207
    Likes Received:
    89
    forgot to put the quotes in the example, the example should be msgbox(spin("{1|2{a|b}|3{a{1|2}|b{1|2}}}"))