0 votes

I am recoding a program from Python into GDScript and am getting stumped at the regular expressions portion. Here the troublesome code:

func replaceVars(vars,text):  
      for loop in range(len(re.findall(r'\{[^{}]*(?=\{)', text))+1):
            for variable in vars:
                if vars[var]:
                    text = re.sub ('\{'+var+r':([^|{}]+)\|([^|{}]+?)\}', r'\1', text)
                else:
                    text = re.sub ('\{'+var+r':([^|{}]+)\|([^|{}]+?)\}', r'\2', text)
        return text

I use this to remove options from a text and display names, pronouns, etc that align with choices that players have already made. For example, "hunger and cold had driven {femalecharacter: Aurelia|Aurelius} from {femalecharacter: her|his} little cubbyhole" would change to: "hunger and cold had driven Aurelius from his little cubbyhole" if the player had chosen a male character.

in Engine by (12 points)

1 Answer

0 votes

Here you go...

func runExample():
    var vars = { "femalecharacter":true , "cold":false }
    var template = "hunger and {cold:cold|boredom} had driven {femalecharacter: Aurelia|Aurelius} from {femalecharacter: her|his} little cubbyhole"
    print ( replaceVars(vars,template) )

func replaceVars(vars,text):
    var regex = RegEx.new()

    for curvar in vars:
        regex.compile("\\{"+curvar+": ?([^|]+)\\|([^}]+)\\}")
        text = regex.sub( text , ("$1" if vars[curvar] else "$2") , true )

    return text

A few notes...

  • GDScript seems to require creating a regex object, then compiling it, then replacing. (Every other language I've used has a shortcut to do that in one command!)

  • Slashes in GDScript strings are significant, so the regex ones need escaping, hence double slashes.

  • GDScript's ternary conditional expression is weird.

  • I simplified the regex to only look for the next delimiter (pipe or brace) and allow an optional space after the colon.

by (15 points)

GDScript's ternary conditional expression is weird.

For reference, it's the same as in Python :)

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.