Skip to content

GLib.MatchInfo

record (struct)

A GMatchInfo is an opaque struct used to return information about matches.

Methods

expand_references

def expand_references(self, string_to_expand: str) -> str | None

Returns a new string containing the text in string_to_expand with references and escape sequences expanded. References refer to the last match done with string against regex and have the same syntax used by Regex.replace.

The string_to_expand must be UTF-8 encoded even if RegexCompileFlags.RAW was passed to Regex.new.

The backreferences are extracted from the string passed to the match function, so you cannot call this function after freeing the string.

match_info may be None in which case string_to_expand must not contain references. For instance "foo\n" does not refer to an actual pattern and '\n' merely will be replaced with \n character, while to expand "\0" (whole match) one needs the result of a match. Use Regex.check_replacement to find out whether string_to_expand contains references.

Parameters:

  • string_to_expand — the string to expand

fetch

def fetch(self, match_num: int) -> str | None

Retrieves the text matching the match_num'th capturing parentheses. 0 is the full text of the match, 1 is the first paren set, 2 the second, and so on.

If match_num is a valid sub pattern but it didn't match anything (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty string is returned.

If the match was obtained using the DFA algorithm, that is using Regex.match_all or Regex.match_all_full, the retrieved string is not that of a set of parentheses but that of a matched substring. Substrings are matched in reverse order of length, so 0 is the longest match.

The string is fetched from the string passed to the match function, so you cannot call this function after freeing the string.

Parameters:

  • match_num — number of the sub expression

fetch_all

def fetch_all(self) -> list[str]

Bundles up pointers to each of the matching substrings from a match and stores them in an array of gchar pointers. The first element in the returned array is the match number 0, i.e. the entire matched text.

If a sub pattern didn't match anything (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty string is inserted.

If the last match was obtained using the DFA algorithm, that is using Regex.match_all or Regex.match_all_full, the retrieved strings are not that matched by sets of parentheses but that of the matched substring. Substrings are matched in reverse order of length, so the first one is the longest match.

The strings are fetched from the string passed to the match function, so you cannot call this function after freeing the string.

fetch_named

def fetch_named(self, name: str) -> str | None

Retrieves the text matching the capturing parentheses named name.

If name is a valid sub pattern name but it didn't match anything (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b") then an empty string is returned.

The string is fetched from the string passed to the match function, so you cannot call this function after freeing the string.

Parameters:

  • name — name of the subexpression

fetch_named_pos

def fetch_named_pos(self, name: str) -> tuple[bool, int, int]

Retrieves the position in bytes of the capturing parentheses named name.

If name is a valid sub pattern name but it didn't match anything (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b") then start_pos and end_pos are set to -1 and True is returned.

As end_pos is set to the byte after the final byte of the match (on success), the length of the match can be calculated as end_pos - start_pos.

Parameters:

  • name — name of the subexpression

fetch_pos

def fetch_pos(self, match_num: int) -> tuple[bool, int, int]

Returns the start and end positions (in bytes) of a successfully matching capture parenthesis.

Valid values for match_num are 0 for the full text of the match, 1 for the first paren set, 2 for the second, and so on.

As end_pos is set to the byte after the final byte of the match (on success), the length of the match can be calculated as end_pos - start_pos.

As a best practice, initialize start_pos and end_pos to identifiable values, such as G_MAXINT, so that you can test if g_match_info_fetch_pos() actually changed the value for a given capture parenthesis.

The parameter match_num corresponds to a matched capture parenthesis. The actual value you use for match_num depends on the method used to generate match_info. The following sections describe those methods.

Methods Using Non-deterministic Finite Automata Matching

The methods Regex.match and Regex.match_full return a MatchInfo using traditional (greedy) pattern matching, also known as Non-deterministic Finite Automaton (NFA) matching. You pass the returned GMatchInfo from these methods to g_match_info_fetch_pos() to determine the start and end positions of capture parentheses. The values for match_num correspond to the capture parentheses in order, with 0 corresponding to the entire matched string.

match_num can refer to a capture parenthesis with no match. For example, the string b matches against the pattern (a)?b, but the capture parenthesis (a) has no match. In this case, g_match_info_fetch_pos() returns true and sets start_pos and end_pos to -1 when called with match_num as 1 (for (a)).

For an expanded example, a regex pattern is (a)?(.*?)the (.*), and a candidate string is glib regexes are the best. In this scenario there are four capture parentheses numbered 0–3: an implicit one for the entire string, and three explicitly declared in the regex pattern.

Given this example, the following table describes the return values from g_match_info_fetch_pos() for various values of match_num.

match_num Contents Return value Returned start_pos Returned end_pos
0 Matches entire string True 0 25
1 Does not match first character True -1 -1
2 All text before the True 0 17
3 All text after the True 21 25
4 Capture paren out of range False Unchanged Unchanged

The following code sample and output implements this example.

#include <glib.h>

int
main (int argc, char *argv[])
{
  g_autoptr(GError) local_error = NULL;
  const char *regex_pattern = "(a)?(.*?)the (.*)";
  const char *test_string = "glib regexes are the best";
  g_autoptr(GRegex) regex = NULL;

  regex = g_regex_new (regex_pattern,
                       G_REGEX_DEFAULT,
                       G_REGEX_MATCH_DEFAULT,
                       &local_error);
  if (regex == NULL)
    {
      g_printerr ("Error creating regex: %s\n", local_error->message);
      return 1;
    }

  g_autoptr(GMatchInfo) match_info = NULL;
  g_regex_match (regex, test_string, G_REGEX_MATCH_DEFAULT, &match_info);

  int n_matched_strings = g_match_info_get_match_count (match_info);

  // Print header line
  g_print ("match_num Contents                  Return value returned start_pos returned end_pos\n");

  // Iterate over each capture paren, including one that is out of range as a demonstration.
  for (int match_num = 0; match_num <= n_matched_strings; match_num++)
    {
      gboolean found_match;
      g_autofree char *paren_string = NULL;
      int start_pos = G_MAXINT;
      int end_pos = G_MAXINT;

      found_match = g_match_info_fetch_pos (match_info,
                                            match_num,
                                            &start_pos,
                                            &end_pos);

      // If no match, display N/A as the found string.
      if (start_pos == G_MAXINT || start_pos == -1)
        paren_string = g_strdup ("N/A");
      else
        paren_string = g_strndup (test_string + start_pos, end_pos - start_pos);

      g_print ("%-9d %-25s %-12d %-18d %d\n", match_num, paren_string, found_match, start_pos, end_pos);
    }

  return 0;
}
match_num Contents                  Return value returned start_pos returned end_pos
0         glib regexes are the best 1            0                  25
1         N/A                       1            -1                 -1
2         glib regexes are          1            0                  17
3         best                      1            21                 25
4         N/A                       0            2147483647         2147483647

Methods Using Deterministic Finite Automata Matching

The methods Regex.match_all and Regex.match_all_full return a GMatchInfo using Deterministic Finite Automaton (DFA) pattern matching. This algorithm detects overlapping matches. You pass the returned GMatchInfo from these methods to g_match_info_fetch_pos() to determine the start and end positions of each overlapping match. Use the method MatchInfo.get_match_count to determine the number of overlapping matches.

For example, a regex pattern is <.*>, and a candidate string is <a> <b> <c>. In this scenario there are three implicit capture parentheses: one for the entire string, one for <a> <b>, and one for <a>.

Given this example, the following table describes the return values from g_match_info_fetch_pos() for various values of match_num.

match_num Contents Return value Returned start_pos Returned end_pos
0 Matches entire string True 0 11
1 Matches <a> <b> True 0 7
2 Matches <a> True 0 3
3 Capture paren out of range False Unchanged Unchanged

The following code sample and output implements this example.

#include <glib.h>

int
main (int argc, char *argv[])
{
  g_autoptr(GError) local_error = NULL;
  const char *regex_pattern = "<.*>";
  const char *test_string = "<a> <b> <c>";
  g_autoptr(GRegex) regex = NULL;

  regex = g_regex_new (regex_pattern,
                       G_REGEX_DEFAULT,
                       G_REGEX_MATCH_DEFAULT,
                       &local_error);
  if (regex == NULL)
    {
      g_printerr ("Error creating regex: %s\n", local_error->message);
      return -1;
    }

  g_autoptr(GMatchInfo) match_info = NULL;
  g_regex_match_all (regex, test_string, G_REGEX_MATCH_DEFAULT, &match_info);

  int n_matched_strings = g_match_info_get_match_count (match_info);

  // Print header line
  g_print ("match_num Contents                  Return value returned start_pos returned end_pos\n");

  // Iterate over each capture paren, including one that is out of range as a demonstration.
  for (int match_num = 0; match_num <= n_matched_strings; match_num++)
    {
      gboolean found_match;
      g_autofree char *paren_string = NULL;
      int start_pos = G_MAXINT;
      int end_pos = G_MAXINT;

      found_match = g_match_info_fetch_pos (match_info, match_num, &start_pos, &end_pos);

      // If no match, display N/A as the found string.
      if (start_pos == G_MAXINT || start_pos == -1)
        paren_string = g_strdup ("N/A");
      else
        paren_string = g_strndup (test_string + start_pos, end_pos - start_pos);

      g_print ("%-9d %-25s %-12d %-18d %d\n", match_num, paren_string, found_match, start_pos, end_pos);
    }

  return 0;
}
match_num Contents                  Return value returned start_pos returned end_pos
0         <a> <b> <c>               1            0                  11
1         <a> <b>                   1            0                  7
2         <a>                       1            0                  3
3         N/A                       0            2147483647         2147483647

Parameters:

  • match_num — number of the capture parenthesis

free

def free(self) -> None

If match_info is not None, calls MatchInfo.unref; otherwise does nothing.

get_match_count

def get_match_count(self) -> int

Retrieves the number of matched substrings (including substring 0, that is the whole matched text), so 1 is returned if the pattern has no substrings in it and 0 is returned if the match failed.

If the last match was obtained using the DFA algorithm, that is using Regex.match_all or Regex.match_all_full, the retrieved count is not that of the number of capturing parentheses but that of the number of matched substrings.

get_regex

def get_regex(self) -> Regex

Returns Regex object used in match_info. It belongs to Glib and must not be freed. Use Regex.ref if you need to keep it after you free match_info object.

get_string

def get_string(self) -> str

Returns the string searched with match_info. This is the string passed to Regex.match_ or Regex.replace so you may not free it before calling this function.

is_partial_match

def is_partial_match(self) -> bool

Usually if the string passed to Regex.match_*() matches as far as it goes, but is too short to match the entire pattern, False is returned. There are circumstances where it might be helpful to distinguish this case from other cases in which there is no match.

Consider, for example, an application where a human is required to type in data for a field with specific formatting requirements. An example might be a date in the form ddmmmyy, defined by the pattern "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$". If the application sees the user’s keystrokes one by one, and can check that what has been typed so far is potentially valid, it is able to raise an error as soon as a mistake is made.

GRegex supports the concept of partial matching by means of the RegexMatchFlags.PARTIAL_SOFT and RegexMatchFlags.PARTIAL_HARD flags. When they are used, the return code for Regex.match_ or Regex.match_full is, as usual, True for a complete match, False otherwise. But, when these functions return False, you can check if the match was partial calling MatchInfo.is_partial_match.

The difference between RegexMatchFlags.PARTIAL_SOFT and RegexMatchFlags.PARTIAL_HARD is that when a partial match is encountered with RegexMatchFlags.PARTIAL_SOFT, matching continues to search for a possible complete match, while with RegexMatchFlags.PARTIAL_HARD matching stops at the partial match. When both RegexMatchFlags.PARTIAL_SOFT and RegexMatchFlags.PARTIAL_HARD are set, the latter takes precedence.

There were formerly some restrictions on the pattern for partial matching. The restrictions no longer apply.

See pcrepartial(3) for more information on partial matching.

matches

def matches(self) -> bool

Returns whether the previous match operation succeeded.

next

def next(self) -> bool

Scans for the next match using the same parameters of the previous call to Regex.match_full or Regex.match_ that returned match_info.

The match is done on the string passed to the match function, so you cannot free it before calling this function.

ref

def ref(self) -> MatchInfo

Increases reference count of match_info by 1.

unref

def unref(self) -> None

Decreases reference count of match_info by 1. When reference count drops to zero, it frees all the memory associated with the match_info structure.