Search code examples
regexsparql

REGEX with letters and underscores in SPARQL


in my SPARQL I have the following bind

BIND(STRAFTER(?ng, "tilastot_") AS ?subj)

It worked when I had string "tilastot_teul" in "?ng" and I needed to set the ending "teul" into "?subj"

But if there are several underscores in "?ng" (like "tilastot_luke_yri_teul") I'll need regex to extract the string after the last underscore. I tried the following:

BIND(STRAFTER(?ng, regex(?ng,([a-z]*_)*) AS ?subj)

But jena-fuseki UI didn't accept it. Can you help ?


Solution

  • You can use replace:

    BIND(replace(?ng, ".*_", "") AS ?subj)
    

    The .*_ pattern matches any zero or more chars as many as possible, and then a _ char, and as the replacement argument is an empty string, the matched text is removed, and all you get is the substring after last _.

    Note: if there is no _ in the string, the output is the input string, as it was, intact.