ballerinaballerina-swan-lake

Does Ballerina regex replace support capture groups?


I want to escape / and . in a string. Ex: for foo/pets/1.2.3 the expected output is foo\/pets\/1\.2\.3

I tried the following:

regex:replaceAll("foo/pets/1.2.3", "(\\.|/)", "\\\\$1");

The output I'm getting is: foo\\$1pets\\$11\\$12\\$13

Is there a way to achieve the expected version?


Solution

  • As Lakshan mentioned, it seems capturing groups were not supported in the regex library, which has been deprecated. However, I was able to get the expected outcome using the lang.regexp library instead using the following code:

    import ballerina/lang.regexp;
    import ballerina/io;
    
    isolated function replaceFunction(regexp:Groups groups) returns string => "\\" + groups[0].substring();
    
    public function main() {
        string str = "foo/pets/1.2.3";
        var result = re `([//\.])`.replaceAll(str, replaceFunction);
        io:println(result); // Output: "foo\/pets\/1\.2\.3"
    }