public static string escape_string (string str, int length = -1)

Escapes the special characters used for regular expressions in string, for instance "a.

b*c" becomes "a\.b\*c". This function is useful to dynamically generate regular expressions.

string can contain nul characters that are replaced with "\0", in this case remember to specify the correct length of string in length.

Example: Regex, escape string:

public int main (string[] args) {
try {
string str = "If I had some duct tape, I could fix that.";
string old = GLib.Regex.escape_string (".*");
string replacement = "duct";

var regex = new GLib.Regex (old);
string result = regex.replace_literal (str, -1, 0, replacement);
// Output:
// ``str: "If I had some duct tape, I could fix that."``
// ``old: "\.\*"``
// ``replacement: "duct"``
// ``result: "If I had some duct tape, I could fix that."``
print ("str: \"%s\"\n", str);
print ("old: \"%s\"\n", old);
print ("replacement: \"%s\"\n", replacement);
print ("result: \"%s\"\n", result);
} catch (GLib.RegexError e) {
GLib.assert_not_reached ();

return 0;

valac --pkg glib-2.0 GLib.Regex.escape_string.vala



the length of string, in bytes, or -1 if string is nul-terminated


the string to escape


a newly-allocated escaped string