Method

GLibRegexreplace_eval

Declaration

gchar*
g_regex_replace_eval (
  const GRegex* regex,
  const gchar* string,
  gssize string_len,
  gint start_position,
  GRegexMatchFlags match_options,
  GRegexEvalCallback eval,
  gpointer user_data,
  GError** error
)

Description

Replaces occurrences of the pattern in regex with the output of eval for that occurrence.

Setting start_position differs from just passing over a shortened string and setting G_REGEX_MATCH_NOTBOL in the case of a pattern that begins with any kind of lookbehind assertion, such as “\b”.

The following example uses g_regex_replace_eval() to replace multiple strings at once:

static gboolean
eval_cb (const GMatchInfo *info,
         GString          *res,
         gpointer          data)
{
  gchar *match;
  gchar *r;

   match = g_match_info_fetch (info, 0);
   r = g_hash_table_lookup ((GHashTable *)data, match);
   g_string_append (res, r);
   g_free (match);

   return FALSE;
}

...

GRegex *reg;
GHashTable *h;
gchar *res;

h = g_hash_table_new (g_str_hash, g_str_equal);

g_hash_table_insert (h, "1", "ONE");
g_hash_table_insert (h, "2", "TWO");
g_hash_table_insert (h, "3", "THREE");
g_hash_table_insert (h, "4", "FOUR");

reg = g_regex_new ("1|2|3|4", 0, 0, NULL);
res = g_regex_replace_eval (reg, text, -1, 0, 0, eval_cb, h, NULL);
g_hash_table_destroy (h);

...
Available since:2.14
This method is not directly available to language bindings.

Parameters

string

Type: An array of gchar

String to perform matches against.

The length of the array is specified in the string_len argument.
The data is owned by the caller of the function.
Each element is a NUL terminated UTF-8 string.
string_len

Type: gssize

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

start_position

Type: gint

Starting index of the string to match, in bytes.

match_options

Type: GRegexMatchFlags

Options for the match.

eval

Type: GRegexEvalCallback

A function to call for each match.

user_data

Type: gpointer

User data to pass to the function.

The argument can be NULL.
The data is owned by the caller of the function.
error

Type: GError **

The return location for a GError*, or NULL.

Return value

Type: gchar*

A newly allocated string containing the replacements.

The caller of the method takes ownership of the data, and is responsible for freeing it.
The value is a NUL terminated UTF-8 string.