How to intialize regex in godot?

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

I’ve searched online and found some solutions, but none of them work.

In python, all you have to do is import re

From the documentation, in GDScript it looks like you do this:

var regex = RegEx.new()
regex.compile("\\w-(\\d+)")

But it’s not working.

Specifically, this is the code (in python) that I want to use:

def getAgeRange(text):
    minString = text.split("-")[0].strip()
    maxString = text.split("-")[1].strip()
    match = re.match(r"([0-9]+)[\s+]?([a-z]+)", maxString)
    matchList = match.groups()
    max = matchList[0]
    max_units = matchList[1]

    match = re.match(r"([0-9]+)\s+([a-z]+)", minString)
    if match:
        matchList = match.groups()
        min = matchList[0]
        min_units = matchList[1]
    else:
        min = minString
        min_units = max_units
    print(str(min) + str(min_units) + "-" + str(max) + str(max_units))

An example of strings I would use would be 3-5 wks and 3 mo-6yo

Does it work if you try another, simpler pattern? Godot uses the PCRE2 library, which may not support some specific regular expressions.

Regular expressions are not standardized and support varies across implementations.

Calinou | 2020-12-01 23:54

Yep, I agree with Calinou here. There are a number of well-vetted and robustregex implementations, but they are not 100% syntactically compatible with each other. Generally, they can all accomplish the same or similar tasks, but you’ll need to take the time to learn the nuances of the regex engine you’re using.

Also, the host of the regex engine (Godot in this case) can introduce an additional layer of complication due to the escaping mechanisms that may be required to support the regex syntax within the scope of a host language.

Bottom line - working with regex is always a bit fiddly until you become comfortable with a specific implementation and environment.

jgodfrey | 2020-12-02 00:26