How to convert RegEx with raw string notation from Python to GDScript?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By godot_n00b

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 {female_character: Aurelia|Aurelius} from {female_character: 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.

:bust_in_silhouette: Reply From: Peter Boughton

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.

GDScript’s ternary conditional expression is weird.

For reference, it’s the same as in Python :slight_smile:

Calinou | 2019-08-19 20:18