glib reference manual - gnomeracarr/glib-docs.pdf · 2009. 5. 18. · imum’. note that ’no’...

616
GLib Reference Manual May 17, 2009

Upload: others

Post on 05-Feb-2021

14 views

Category:

Documents


0 download

TRANSCRIPT

  • GLib Reference Manual

    May 17, 2009

  • GLib Reference Manual

    ii

  • Contents

    1 GLib Overview 11.1 Compiling the GLib package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Cross-compiling the GLib package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.3 Compiling GLib Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.4 Running GLib Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.5 Changes to GLib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.6 Regular expression syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.7 Mailing lists and bug reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

    2 GLib Fundamentals 332.1 Version Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332.2 Basic Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352.3 Limits of Basic Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402.4 Standard Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442.5 Type Conversion Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482.6 Byte Order Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502.7 Numerical Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602.8 Miscellaneous Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632.9 Atomic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

    3 GLib Core Application Support 773.1 The Main Event Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773.2 Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1043.3 Thread Pools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1313.4 Asynchronous Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1363.5 Dynamic Loading of Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1433.6 Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1473.7 IO Channels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1543.8 Error Reporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1713.9 Message Output and Debugging Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 1783.10 Message Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

    4 GLib Utilities 1894.1 String Utility Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1894.2 Character Set Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2134.3 Unicode Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2234.4 Base64 Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2484.5 Data Checksums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2514.6 Internationalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2554.7 Date and Time Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2604.8 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2764.9 Hook Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2814.10 Miscellaneous Utility Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2914.11 Lexical Scanner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3044.12 Automatic String Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3174.13 Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3204.14 Spawning Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3224.15 File Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3304.16 URI Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3434.17 Shell-related Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3464.18 Commandline option parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3474.19 Glob-style pattern matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3614.20 Perl-compatible regular expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3644.21 Simple XML Subset Parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386

    iii

  • CONTENTS

    4.22 Key-value file parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3964.23 Bookmark file parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4194.24 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4364.25 Windows Compatibility Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449

    5 GLib Data Types 4555.1 Memory Slices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4555.2 Memory Chunks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4595.3 Doubly-Linked Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4665.4 Singly-Linked Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4785.5 Double-ended Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4875.6 Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4985.7 Trash Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5095.8 Hash Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5105.9 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5235.10 String Chunks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5335.11 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5355.12 Pointer Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5425.13 Byte Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5485.14 Balanced Binary Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5525.15 N-ary Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5585.16 Quarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5705.17 Keyed Data Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5725.18 Datasets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5765.19 Relations and Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5805.20 Caches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5845.21 Memory Allocators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588

    6 GLib Tools 5916.1 glib-gettextize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5916.2 gtester . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5916.3 gtester-report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592

    Index 593

    iv

  • List of Figures

    3 GLib Core Application Support3.1 States of a Main Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

    4 GLib Utilities4.1 Conversion between File Name Encodings . . . . . . . . . . . . . . . . . . . . . . . . . . . 215

    v

  • List of Tables

    1 GLib Overview1.1 Metacharacters outside square brackets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.2 Metacharacters inside square brackets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.3 Non-printing characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.4 Non-printing characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.5 Generic characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.6 Generic character types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.7 Property codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151.8 Simple assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161.9 Posix classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191.10 Option settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191.11 Abbreviations for quantifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

    vii

  • Chapter 1

    GLib Overview

    GLib is a general-purpose utility library, which provides many useful data types, macros, type con-versions, string utilities, file utilities, a main loop abstraction, and so on. It works on many UNIX-likeplatforms, Windows, OS/2 and BeOS. GLib is released under the GNU Library General Public License(GNU LGPL).

    The general policy of GLib is that all functions are invisibly threadsafe with the exception of datastructure manipulation functions, where, if you have two threads manipulating the same data structure,they must use a lock to synchronize their operation.

    1.1 Compiling the GLib package

    Name

    Compiling the GLib Package – How to compile GLib itself

    Building the Library on UNIX

    On UNIX, GLib uses the standard GNU build system, using autoconf for package configuration andresolving portability issues, automake for building makefiles that comply with the GNU Coding Stan-dards, and libtool for building shared libraries on multiple platforms. The normal sequence for compil-ing and installing the GLib library is thus:

    ./configuremakemake install

    The standard options provided by GNU autoconf may be passed to the configure script. Please seethe autoconf documentation or run ./configure --help for information about the standard options.

    The GTK+ documentation contains further details about the build process and ways to influence it.

    Dependencies

    Before you can compile the GLib library, you need to have various other tools and libraries installed onyour system. The two tools needed during the build process (as differentiated from the tools used inwhen creating GLib mentioned above such as autoconf) are pkg-config and GNU make.

    • pkg-config is a tool for tracking the compilation flags needed for libraries that are used by the GLiblibrary. (For each library, a small .pc text file is installed in a standard location that contains thecompilation flags needed for that library along with version number information.) The version ofpkg-config needed to build GLib is mirrored in the dependencies directory on the GTK+ FTPsite.

    • The GTK+ makefiles will mostly work with different versions of make, however, there tends to bea few incompatibilities, so the GTK+ team recommends installing GNU make if you don’t alreadyhave it on your system and using it. (It may be called gmake rather than make.)

    1

    file:../gtk/gtk-building.htmlhttp://www.freedesktop.org/software/pkgconfig/ftp://ftp.gtk.org/pub/gtk/v2.2/ftp://ftp.gtk.org/pub/gtk/v2.2/http://www.gnu.org/software/make

  • CHAPTER 1. GLIB OVERVIEW 1.1. COMPILING THE GLIB PACKAGE

    GLib depends on a number of other libraries.

    • The GNU libiconv library is needed to build GLib if your system doesn’t have the iconv() func-tion for doing conversion between character encodings. Most modern systems should have ic-onv(), however many older systems lack an iconv() implementation. On such systems, youmust install the libiconv library. This can be found at: http://www.gnu.org/software/libiconv.

    If your system has an iconv() implementation but you want to use libiconv instead, you canpass the --with-libiconv option to configure. This forces libiconv to be used.

    Note that if you have libiconv installed in your default include search path (for instance, in /usr/local/), but don’t enable it, you will get an error while compiling GLib because the iconv.hthat libiconv installs hides the system iconv.

    If you are using the native iconv implementation on Solaris instead of libiconv, you’ll need to makesure that you have the converters between locale encodings and UTF-8 installed. At a minimumyou’ll need the SUNWuiu8 package. You probably should also install the SUNWciu8, SUNWhiu8,SUNWjiu8, and SUNWkiu8 packages.

    The native iconv on Compaq Tru64 doesn’t contain support for UTF-8, so you’ll need to use GNUlibiconv instead. (When using GNU libiconv for GLib, you’ll need to use GNU libiconv for GNUgettext as well.) This probably applies to related operating systems as well.

    • The libintl library from the GNU gettext package is needed if your system doesn’t have the get-text() functionality for handling message translation databases.

    • A thread implementation is needed, unless you want to compile GLib without thread support,which is not recommended. The thread support in GLib can be based upon several native threadimplementations, e.g. POSIX threads, DCE threads or Solaris threads.

    • GRegex uses the PCRE library for regular expression matching. The default is to use the internalversion of PCRE that is patched to use GLib for memory management and Unicode handling. Ifyou prefer to use the system-supplied PCRE library you can pass the --with-pcre=system optionto configure, but it is not recommended.

    • The optional extended attribute support in GIO requires the getxattr() family of functions that maybe provided by glibc or by the standalone libattr library. To build GLib without extended attributesupport, use the --disable-xattr configure option.

    • The optional SELinux support in GIO requires libselinux. To build GLib without SELinux support,use the --disable-selinux configure option.

    Extra Configuration Options

    In addition to the normal options, the configure script in the GLib library supports these additionalarguments:

    configure [--enable-debug=[no|minimum|yes]] [--disable-gc-friendly | --enable-gc-friendly] [--disable-mem-pools | --enable-mem-pools] [--disable-threads | --enable-threads] [--with-threads=[none|posix|dce|win32]][--disable-regex | --enable-regex] [--with-pcre=[internal|system]] [--disable-included-printf | --enable-included-printf] [--disable-visibility | --enable-visibility] [--disable-gtk-doc | --enable-gtk-doc] [--disable-man | --enable-man] [--disable-xattr | --enable-xattr] [--disable-selinux | --enable-selinux]

    --enable-debug Turns on various amounts of debugging support. Setting this to ’no’ disables g_assert(),g_return_if_fail(), g_return_val_if_fail() and all cast checks between different object types. Setting it to’minimum’ disables only cast checks. Setting it to ’yes’ enables runtime debugging. The default is ’min-imum’. Note that ’no’ is fast, but dangerous as it tends to destabilize even mostly bug-free software bychanging the effect of many bugs from simple warnings into fatal crashes. Thus --enable-debug=noshould not be used for stable releases of GLib.

    --disable-gc-friendly and --enable-gc-friendly By default, and with --disable-gc-friendly aswell, Glib does not clear the memory for certain objects before they are freed. For example, Glib maydecide to recycle GList nodes by putting them in a free list. However, memory profiling and debuggingtools like Valgrind work better if an application does not keep dangling pointers to freed memory (eventhough these pointers are no longer dereferenced), or invalid pointers inside uninitialized memory. The--enable-gc-friendly option makes Glib clear memory in these situations:

    2

    http://www.gnu.org/software/libiconv/http://www.gnu.org/software/libiconvhttp://www.gnu.org/software/gettexthttp://www.pcre.org/http://www.valgrind.org

  • CHAPTER 1. GLIB OVERVIEW 1.1. COMPILING THE GLIB PACKAGE

    • When shrinking a GArray, Glib will clear the memory no longer available in the array: shrink anarray from 10 bytes to 7, and the last 3 bytes will be cleared. This includes removals of single andmultiple elements.

    • When growing a GArray, Glib will clear the new chunk of memory. Grow an array from 7 bytes to10 bytes, and the last 3 bytes will be cleared.

    • The above applies to GPtrArray as well.

    • When freeing a node from a GHashTable, Glib will first clear the node, which used to have pointersto the key and the value stored at that node.

    • When destroying or removing a GTree node, Glib will clear the node, which used to have pointersto the node’s value, and the left and right subnodes.

    Since clearing the memory has a cost, --disable-gc-friendly is the default.--disable-mem-pools and --enable-mem-pools Many small chunks of memory are often allocated

    via collective pools in GLib and are cached after release to speed up reallocations. For sparse memorysystems this behaviour is often inferior, so memory pools can be disabled to avoid excessive cachingand force atomic maintenance of chunks through the g_malloc() and g_free() functions. Codecurrently affected by this:

    • GList, GSList, GNode, GHash allocations. The functions g_list_push_allocator(), g_list_pop_allocator(),g_slist_push_allocator(), g_slist_pop_allocator(), g_node_push_allocator() and g_node_pop_allocator()are not available

    • GMemChunks become basically non-effective

    • GSignal disables all caching (potentially very slow)

    • GType doesn’t honour the GTypeInfo n_preallocs field anymore

    • the GBSearchArray flag G_BSEARCH_ALIGN_POWER2 becomes non-functional

    --disable-threads and --enable-threads Do not compile GLib to be multi thread safe. GLib will beslightly faster then. This is however not recommended, as many programs rely on GLib being multithread safe.

    --with-threads Specify a thread implementation to use.

    • ’posix’ and ’dce’ can be used interchangeable to mean the different versions of Posix threads.configure tries to find out, which one is installed.

    • ’none’ means that GLib will be thread safe, but does not have a default thread implementation.This has to be supplied to g_thread_init() by the programmer.

    --disable-regex and --enable-regex Do not compile GLib with regular expression support. GLib willbe smaller because it will not need the PCRE library. This is however not recommended, as programsmay need GRegex.

    --with-pcre Specify whether to use the internal or the system-supplied PCRE library.

    • ’internal’ means that GRegex will be compiled to use the internal PCRE library.

    • ’system’ means that GRegex will be compiled to use the system-supplied PCRE library.

    Using the internal PCRE is the preferred solution:

    • System-supplied PCRE has a separated copy of the big tables used for Unicode handling.

    • Some systems have PCRE libraries compiled without some needed features, such as UTF-8 andUnicode support.

    • PCRE uses some global variables for memory management and other features. In the rare case ofa program using both GRegex and PCRE (maybe indirectly through a library), this variables couldlead to problems when they are modified.

    3

  • CHAPTER 1. GLIB OVERVIEW 1.2. CROSS-COMPILING THE GLIB PACKAGE

    --disable-included-printf and --enable-included-printf By default the configure script will try toauto-detect whether the C library provides a suitable set of printf() functions. In detail, config-ure checks that the semantics of snprintf() are as specified by C99 and that positional parametersas specified in the Single Unix Specification are supported. If this not the case, GLib will include animplementation of the printf() family. These options can be used to explicitly control whether animplementation fo the printf() family should be included or not.

    --disable-visibility and --enable-visibility By default, GLib uses ELF visibility attributes to optimizePLT table entries if the compiler supports ELF visibility attributes. A side-effect of the way in which thisis currently implemented is that any header change forces a full recompilation, and missing includesmay go unnoticed. Therefore, it makes sense to turn this feature off while doing GLib development,even if the compiler supports ELF visibility attributes. The --disable-visibility option allows todo that.

    --disable-gtk-doc and --enable-gtk-doc By default the configure script will try to auto-detect whetherthe gtk-doc package is installed. If it is, then it will use it to extract and build the documentation for theGLib library. These options can be used to explicitly control whether gtk-doc should be used or not. Ifit is not used, the distributed, pre-generated HTML files will be installed instead of building them onyour machine.

    --disable-man and --enable-man By default the configure script will try to auto-detect whether xslt-proc and the necessary Docbook stylesheets are installed. If they are, then it will use them to rebuildthe included man pages from the XML sources. These options can be used to explicitly control whetherman pages should be rebuilt used or not. The distribution includes pre-generated man pages.

    --disable-xattr and --enable-xattr By default the configure script will try to auto-detect whether thegetxattr() family of functions is available. If it is, then extended attribute support will be included in GIO.These options can be used to explicitly control whether extended attribute support should be includedor not. getxattr() and friends can be provided by glibc or by the standalone libattr library.

    --disable-selinux and --enable-selinux By default the configure script will auto-detect if libselinuxis available and include SELinux support in GIO if it is. These options can be used to explicitly controlwhether SELinxu support should be included.

    1.2 Cross-compiling the GLib package

    Name

    Cross-compiling the GLib Package – How to cross-compile GLib

    Building the Library for a different architecture

    Cross-compilation is the process of compiling a program or library on a different architecture or operat-ing system then it will be run upon. GLib is slightly more difficult to cross-compile than many packagesbecause much of GLib is about hiding differences between different systems.

    These notes cover things specific to cross-compiling GLib; for general information about cross-compilation, see the autoconf info pages.

    GLib tries to detect as much information as possible about the target system by compiling and linkingprograms without actually running anything; however, some information GLib needs is not availablethis way. This information needs to be provided to the configure script via a "cache file" or by settingthe cache variables in your environment.

    As an example of using a cache file, to cross compile for the "MingW32" Win32 runtine environmenton a Linux system, create a file ’win32.cache’ with the following contents:

    glib_cv_long_long_format=I64glib_cv_stack_grows=no

    Then execute the following commands:

    PATH=/path/to/mingw32-compiler/bin:$PATHchmod a-w win32.cache # prevent configure from changing it./configure --cache-file=win32.cache --host=mingw32

    The complete list of cache file variables follows. Most of these won’t need to be set in most cases.

    4

  • CHAPTER 1. GLIB OVERVIEW 1.3. COMPILING GLIB APPLICATIONS

    Cache file variables

    glib_cv_long_long_format=[ll/q/I64] Format used by printf() and scanf() for 64 bit integers. "ll"is the C99 standard, and what is used by the ’trio’ library that GLib builds if your printf() is insuffi-ciently capable. Doesn’t need to be set if you are compiling using trio.

    glib_cv_stack_grows=[yes/no] Whether the stack grows up or down. Most places will want "no", Afew architectures, such as PA-RISC need "yes".

    glib_cv_working_bcopy=[yes/no] Whether your bcopy() can handle overlapping copies. Onlyneeds to be set if you don’t have memmove(). (Very unlikely)

    glib_cv_sane_realloc=[yes/np] Whether your realloc() conforms to ANSI C and can handle NU-LL as the first argument. Defaults to "yes" and probably doesn’t need to be set.

    glib_cv_have_strlcpy=[yes/no] Whether you have strlcpy() that matches OpenBSD. Defaults to"no", which is safe, since GLib uses a built-in version in that case.

    glib_cv_va_val_copy=[yes/no] Whether va_list can be copied as a pointer. If set to "no", then memc-opy() will be used. Only matters if you don’t have va_copy() or __va_copy(). (So, doesn’t matterfor GCC.) Defaults to "yes" which is slightly more common than "no".

    glib_cv_rtldglobal_broken=[yes/no] Whether you have a bug found in OSF/1 v5.0. Defaults to"no".

    glib_cv_uscore=[yes/no] Whether an underscore needs to be prepended to symbols when lookingthem up via dlsym(). Only needs to be set if your system uses dlopen()/dlsym().

    ac_cv_func_posix_getpwuid_r=[yes/no] Whether you have a getpwuid_r function (in your C li-brary, not your thread library) that conforms to the POSIX spec. (Takes a ’struct passwd **’ as the finalargument)

    ac_cv_func_nonposix_getpwuid_r=[yes/no] Whether you have some variant of getpwuid_r()that doesn’t conform to to the POSIX spec, but GLib might be able to use (or might segfault.) Onlyneeds to be set if ac_cv_func_posix_getpwuid_r is not set. It’s safest to set this to "no".

    ac_cv_func_posix_getgrgid_r=[yes/no] Whether you have a getgrgid_r function that conforms tothe POSIX spec.

    glib_cv_use_pid_surrogate=[yes/no] Whether to use a setpriority() on the PID of the thread asa method for setting the priority of threads. This only needs to be set when using POSIX threads.

    ac_cv_func_printf_unix98=[yes/no] Whether your printf() family supports Unix98 style %N$ po-sitional parameters. Defaults to "no".

    ac_cv_func_vsnprintf_c99=[yes/no] Whether you have a vsnprintf() with C99 semantics. (C99semantics means returning the number of bytes that would have been written had the output buffer hadenough space.) Defaults to "no".

    1.3 Compiling GLib Applications

    Name

    Compiling GLib Applications – How to compile your GLib application

    Compiling GLib Applications on UNIX

    To compile a GLib application, you need to tell the compiler where to find the GLib header files andlibraries. This is done with the pkg-config utility.

    The following interactive shell session demonstrates how pkg-config is used (the actual output onyour system may be different):

    $ pkg-config --cflags glib-2.0-I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include

    $ pkg-config --libs glib-2.0-L/usr/lib -lm -lglib-2.0

    If your application uses threads or GObject features, it must be compiled and linked with the optionsreturned by the following pkg-config invocations:

    $ pkg-config --cflags --libs gthread-2.0$ pkg-config --cflags --libs gobject-2.0

    5

  • CHAPTER 1. GLIB OVERVIEW 1.4. RUNNING GLIB APPLICATIONS

    If your application uses modules, it must be compiled and linked with the options returned by oneof the following pkg-config invocations:

    $ pkg-config --cflags --libs gmodule-no-export-2.0$ pkg-config --cflags --libs gmodule-2.0

    The difference between the two is that gmodule-2.0 adds --export-dynamic to the linker flags, whichis often not needed.

    The simplest way to compile a program is to use the "backticks" feature of the shell. If you enclosea command in backticks (not single quotes), then its output will be substituted into the command linebefore execution. So to compile a GLib Hello, World, you would type the following:

    $ cc ‘pkg-config --cflags --libs glib-2.0‘ hello.c -o hello

    If you want to make sure that your program doesn’t use any deprecated functions, you can definethe preprocessor symbol G_DISABLE_DEPRECATED by using the command line option -DG_DISAB-LE_DEPRECATED=1.

    The recommended way of using GLib has always been to only include the toplevel headers glib.h,glib-object.h, gio.h. Starting with 2.17, GLib enforces this by generating an error when individualheaders are directly included. To help with the transition, the enforcement is not turned on by defaultfor GLib headers (it is turned on for GObject and GIO). To turn it on, define the preprocessor symbolG_DISABLE_SINGLE_INCLUDES by using the command line option -DG_DISABLE_SINGLE_INCL-UDES.

    1.4 Running GLib Applications

    Name

    Running GLib Applications – How to run and debug your GLib application

    Running and debugging GLib Applications

    Environment variables

    GLib inspects a few of environment variables in addition to standard variables like LANG, PATH or HOME.G_FILENAME_ENCODINGThis environment variable can be set to a comma-separated list of character set names. GLib assumes

    that filenames are encoded in the first character set from that list rather than in UTF-8. The special token"@locale" can be used to specify the character set for the current locale.

    G_BROKEN_FILENAMESIf this environment variable is set, GLib assumes that filenames are in the locale encoding rather than

    in UTF-8. G_FILENAME_ENCODING takes priority over G_BROKEN_FILENAMES.G_MESSAGES_PREFIXEDA list of log levels for which messages should be prefixed by the program name and PID of the

    application. The default is to prefix everything except G_LOG_LEVEL_MESSAGE and G_LOG_LEVEL_-INFO.

    G_DEBUGIf GLib has been configured with --enable-debug=yes, this variable can be set to a list of debug

    options, which cause GLib to print out different types of debugging information.

    fatal_warnings Causes GLib to abort the program at the first call to g_warning() or g_critical(). Thisoption is special in that it doesn’t require GLib to be configured with debugging support.

    fatal_criticals Causes GLib to abort the program at the first call to g_critical(). This option is special inthat it doesn’t require GLib to be configured with debugging support.

    gc-friendly Newly allocated memory that isn’t directly initialized, as well as memory being freed willbe reset to 0. The point here is to allow memory checkers and similar programs that use bohem GCalike algorithms to produce more accurate results. This option is special in that it doesn’t requireGLib to be configured with debugging support.

    6

  • CHAPTER 1. GLIB OVERVIEW 1.4. RUNNING GLIB APPLICATIONS

    resident-modules All modules loaded by GModule will be made resident. This can be useful for track-ing memory leaks in modules which are later unloaded; but it can also hide bugs where code isaccessed after the module would have normally been unloaded. This option is special in that itdoesn’t require GLib to be configured with debugging support.

    bind-now-modules All modules loaded by GModule will bind their symbols at load time, even whenthe code uses %G_MODULE_BIND_LAZY. This option is special in that it doesn’t require GLib tobe configured with debugging support.

    The special value all can be used to turn on all debug options. The special value help can be used toprint all available options.

    G_SLICEThis environment variable allows reconfiguration of the GSlice memory allocator.

    always-malloc This will cause all slices allocated through g_slice_alloc() and released by g_slice_free1()to be actually allocated via direct calls to g_malloc() and g_free(). This is most useful for mem-ory checkers and similar programs that use Bohem GC alike algorithms to produce more accurateresults. It can also be in conjunction with debugging features of the system’s malloc implemen-tation such as glibc’s MALLOC_CHECK_=2 to debug erroneous slice allocation code, allthoughdebug-blocks usually is a better suited debugging tool.

    debug-blocks Using this option (present since GLib-2.13) engages extra code which performs sanitychecks on the released memory slices. Invalid slice adresses or slice sizes will be reported and leadto a program halt. This option is for debugging scenarios. In particular, client packages sportingtheir own test suite should always enable this option when running tests. Global slice validation is en-sured by storing size and address information for each allocated chunk, and maintaining a globalhash table of that data. That way, multi-thread scalability is given up, and memory consumptionis increased. However, the resulting code usually performs acceptably well, possibly better thanwith comparable memory checking carried out using external tools. An example of a memory cor-ruption scenario that cannot be reproduced with G_SLICE=always-malloc, but will be caughtby G_SLICE=debug-blocks is as follows:

    void *slist = g_slist_alloc(); /* void* gives up type-safety */g_list_free (slist); /* corruption: sizeof (GSList) != ←↩

    sizeof (GList) */

    The special value all can be used to turn on all options. The special value help can be used to print allavailable options.

    G_RANDOM_VERSIONIf this environment variable is set to ’2.0’, the outdated pseudo-random number seeding and genera-

    tion algorithms from GLib-2.0 are used instead of the new better ones. Use the GLib-2.0 algorithms onlyif you have sequences of numbers generated with Glib-2.0 that you need to reproduce exactly.

    LIBCHARSET_ALIAS_DIRAllows to specify a nonstandard location for the charset.aliases file that is used by the character

    set conversion routines. The default location is the libdir specified at compilation time.

    Locale

    A number of interfaces in GLib depend on the current locale in which an application is running. There-fore, most GLib-using applications should call setlocale (LC_ALL, "") to set up the current locale.

    On Windows, in a C program there are several locale concepts that not necessarily are synchronized.On one hand, there is the system default ANSI code-page, which determines what encoding is used forfile names handled by the C library’s functions and the Win32 API. (We are talking about the "narrow"functions here that take character pointers, not the "wide" ones.)

    On the other hand, there is the C library’s current locale. The character set (code-page) used by that isnot necessarily the same as the system default ANSI code-page. Strings in this character set are returnedby functions like strftime().

    7

  • CHAPTER 1. GLIB OVERVIEW 1.5. CHANGES TO GLIB

    Traps and traces

    Some code portions contain trap variables that can be set during debugging time if GLib has been con-figured with --enable-debug=yes. Such traps lead to immediate code halts to examine the currentprogram state and backtrace.

    Currently, the following trap variables exist:

    static volatile gulong g_trap_free_size;static volatile gulong g_trap_realloc_size;static volatile gulong g_trap_malloc_size;

    If set to a size > 0, g_free(), g_realloc() and g_malloc() will be intercepted if the size matches the size ofthe corresponding memory block. This will only work with g_mem_set_vtable (glib_mem_pro-filer_table) upon startup though, because memory profiling is required to match on the memoryblock sizes.

    Note that many modern debuggers support conditional breakpoints, which achieve pretty much thesame. E.g. in gdb, you can do

    break g_malloccondition 1 n_bytes == 20

    to break only on g_malloc() calls where the size of the allocated memory block is 20.

    Memory statistics

    g_mem_profile() will output a summary g_malloc() memory usage, if memory profiling has been en-abled by calling g_mem_set_vtable (glib_mem_profiler_table) upon startup.

    If GLib has been configured with --enable-debug=yes, then g_slice_debug_tree_statistics() canbe called in a debugger to output details about the memory usage of the slice allocator.

    1.5 Changes to GLib

    Name

    Changes to GLib – Incompatible changes made between successing versions of GLib

    Incompatible changes from 2.0 to 2.2

    • GLib changed the seeding algorithm for the pseudo-random number generator Mersenne Twister,as used by GRand and GRandom. This was necessary, because some seeds would yield very badpseudo-random streams. Also the pseudo-random integers generated by g_rand*_int_rang-e() will have a slightly better equal distribution with the new version of GLib.

    Further information can be found at the website of the Mersenne Twister random number gener-ator at http://www.math.keio.ac.jp/~matumoto/emt.html.

    The original seeding and generation algorithms, as found in GLib 2.0.x, can be used instead of thenew ones by setting the environment variable G_RANDOM_VERSION to the value of ’2.0’. Use theGLib-2.0 algorithms only if you have sequences of numbers generated with Glib-2.0 that you needto reproduce exactly.

    Incompatible changes from 1.2 to 2.0

    The GNOME 2.0 porting guide on http://developer.gnome.org has some more detailed discussion ofporting from 1.2 to 2.0. See the section on GLib.

    • The event loop functionality GMain has extensively been revised to support multiple separatemain loops in separate threads. All sources (timeouts, idle functions, etc.) are associated with aGMainContext.

    Compatibility functions exist so that most application code dealing with the main loop will con-tinue to work. However, code that creates new custom types of sources will require modification.

    The main changes here are:

    8

    http://www.math.keio.ac.jp/~matumoto/emt.htmlhttp://developer.gnome.org/dotplan/porting/http://developer.gnome.org

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    – Sources are now exposed as GSource *, rather than simply as numeric ids.

    – New types of sources are created by structure "derivation" from GSource, so the source_d-ata parameter to the GSource virtual functions has been replaced with a GSource *.

    – Sources are first created, then later added to a specific GMainContext.

    – Dispatching has been modified so both the callback and data are passed in to the dispatc-h() virtual function.

    To go along with this change, the vtable for GIOChannel has changed and add_watch() has beenreplaced by create_watch().

    • g_list_foreach() and g_slist_foreach() have been changed so they are now safe againstremoval of the current item, not the next item.

    It’s not recommended to mutate the list in the callback to these functions in any case.

    • GDate now works in UTF-8, not in the current locale. If you want to use it with the encoding ofthe locale, you need to convert strings using g_locale_to_utf8() first.

    • g_strsplit() has been fixed to:

    – include trailing empty tokens, rather than stripping them

    – split into a maximum of max_tokens tokens, rather than max_tokens + 1

    Code depending on either of these bugs will need to be fixed.

    • Deprecated functions that got removed: g_set_error_handler(), g_set_warning_handl-er(), g_set_message_handler(), use g_log_set_handler() instead.

    1.6 Regular expression syntax

    Name

    Regular expression syntax – Syntax and semantics of the regular expressions supported by GRegex

    GRegex regular expression details

    A regular expression is a pattern that is matched against a string from left to right. Most characters standfor themselves in a pattern, and match the corresponding characters in the string. As a trivial example,the pattern

    The quick brown fox

    matches a portion of a string that is identical to itself. When caseless matching is specified (theG_REGEX_CASELESS flag), letters are matched independently of case.

    The power of regular expressions comes from the ability to include alternatives and repetitions inthe pattern. These are encoded in the pattern by the use of metacharacters, which do not stand forthemselves but instead are interpreted in some special way.

    There are two different sets of metacharacters: those that are recognized anywhere in the pattern ex-cept within square brackets, and those that are recognized in square brackets. Outside square brackets,the metacharacters are as follows:

    Part of a pattern that is in square brackets is called a "character class". In a character class the onlymetacharacters are:

    Backslash

    The backslash character has several uses. Firstly, if it is followed by a non-alphanumeric character, ittakes away any special meaning that character may have. This use of backslash as an escape characterapplies both inside and outside character classes.

    For example, if you want to match a * character, you write \* in the pattern. This escaping actionapplies whether or not the following character would otherwise be interpreted as a metacharacter, so

    9

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    Table 1.1 Metacharacters outside square brackets

    Character Meaning\ general escape character with several usesˆ assert start of string (or line, in multiline mode)$ assert end of string (or line, in multiline mode)

    . match any character except newline (bydefault)[ start character class definition| start of alternative branch( start subpattern) end subpattern

    ? extends the meaning of (, or 0/1 quantifier, orquantifier minimizer* 0 or more quantifier

    + 1 or more quantifier, also "possessivequantifier"{ start min/max quantifier

    Table 1.2 Metacharacters inside square brackets

    Character Meaning\ general escape characterˆ negate the class, but only if the first character- indicates character range

    [ POSIX character class (only if followed byPOSIX syntax)] terminates the character class

    it is always safe to precede a non-alphanumeric with backslash to specify that it stands for itself. Inparticular, if you want to match a backslash, you write \\.

    If a pattern is compiled with the G_REGEX_EXTENDED option, whitespace in the pattern (other thanin a character class) and characters between a # outside a character class and the next newline are ig-nored. An escaping backslash can be used to include a whitespace or # character as part of the pattern.

    If you want to remove the special meaning from a sequence of characters, you can do so by puttingthem between \Q and \E. The \Q...\E sequence is recognized both inside and outside character classes.

    Non-printing characters

    A second use of backslash provides a way of encoding non-printing characters in patterns in a visiblemanner. There is no restriction on the appearance of non-printing characters, apart from the binary zerothat terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to useone of the following escape sequences than the binary character it represents:

    Table 1.3 Non-printing characters

    Escape Meaning\a alarm, that is, the BEL character (hex 07)\cx "control-x", where x is any character\e escape (hex 1B)\f formfeed (hex 0C)\n newline (hex 0A)\r carriage return (hex 0D)\t tab (hex 09)

    \ddd character with octal code ddd, or backreference\xhh character with hex code hh

    \x{hhh..} character with hex code hhh..

    The precise effect of \cx is as follows: if x is a lower case letter, it is converted to upper case. Then

    10

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    bit 6 of the character (hex 40) is inverted. Thus \cz becomes hex 1A, but \c{ becomes hex 3B, while \c;becomes hex 7B.

    After \x, from zero to two hexadecimal digits are read (letters can be in upper or lower case). Anynumber of hexadecimal digits may appear between \x{ and }, but the value of the character code must beless than 2**31 (that is, the maximum hexadecimal value is 7FFFFFFF). If characters other than hexadeci-mal digits appear between \x{ and }, or if there is no terminating }, this form of escape is not recognized.Instead, the initial \x will be interpreted as a basic hexadecimal escape, with no following digits, givinga character whose value is zero.

    Characters whose value is less than 256 can be defined by either of the two syntaxes for \x. There isno difference in the way they are handled. For example, \xdc is exactly the same as \x{dc}.

    After \0 up to two further octal digits are read. If there are fewer than two digits, just those that arepresent are used. Thus the sequence \0\x\07 specifies two binary zeros followed by a BEL character(code value 7). Make sure you supply two digits after the initial zero if the pattern character that followsis itself an octal digit.

    The handling of a backslash followed by a digit other than 0 is complicated. Outside a characterclass, GRegex reads it and any following digits as a decimal number. If the number is less than 10, orif there have been at least that many previous capturing left parentheses in the expression, the entiresequence is taken as a back reference. A description of how this works is given later, following thediscussion of parenthesized subpatterns.

    Inside a character class, or if the decimal number is greater than 9 and there have not been that manycapturing subpatterns, GRegex re-reads up to three octal digits following the backslash, and uses themto generate a data character. Any subsequent digits stand for themselves. For example:

    Table 1.4 Non-printing characters

    Escape Meaning\040 is another way of writing a space

    \40 is the same, provided there are fewer than 40previous capturing subpatterns\7 is always a back reference

    \11 might be a back reference, or another way ofwriting a tab\011 is always a tab

    \0113 is a tab followed by the character "3"

    \113 might be a back reference, otherwise thecharacter with octal code 113

    \377 might be a back reference, otherwise the byteconsisting entirely of 1 bits

    \81 is either a back reference, or a binary zerofollowed by the two characters "8" and "1"

    Note that octal values of 100 or greater must not be introduced by a leading zero, because no morethan three octal digits are ever read.

    All the sequences that define a single character can be used both inside and outside character classes.In addition, inside a character class, the sequence \b is interpreted as the backspace character (hex 08),and the sequences \R and \X are interpreted as the characters "R" and "X", respectively. Outside acharacter class, these sequences have different meanings (see below).

    Absolute and relative back references

    The sequence \g followed by a positive or negative number, optionally enclosed in braces, is an absoluteor relative back reference. Back references are discussed later, following the discussion of parenthesizedsubpatterns.

    Generic character types

    Another use of backslash is for specifying generic character types. The following are always recognized:Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any

    given character matches one, and only one, of each pair.

    11

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    Table 1.5 Generic charactersEscape Meaning

    \d any decimal digit\D any character that is not a decimal digit\s any whitespace character\S any character that is not a whitespace character\w any "word" character\W any "non-word" character

    These character type sequences can appear both inside and outside character classes. They eachmatch one character of the appropriate type. If the current matching point is at the end of the passedstring, all of them fail, since there is no character to match.

    For compatibility with Perl, \s does not match the VT character (code 11). This makes it differentfrom the the POSIX "space" class. The \s characters are HT (9), LF (10), FF (12), CR (13), and space (32).

    A "word" character is an underscore or any character less than 256 that is a letter or digit.Characters with values greater than 128 never match \d, \s, or \w, and always match \D, \S, and

    \W.

    Newline sequences

    Outside a character class, the escape sequence \R matches any Unicode newline sequence. This partic-ular group matches either the two-character sequence CR followed by LF, or one of the single charactersLF (linefeed, U+000A), VT (vertical tab, U+000B), FF (formfeed, U+000C), CR (carriage return, U+000D),NEL (next line, U+0085), LS (line separator, U+2028), or PS (paragraph separator, U+2029). The two-character sequence is treated as a single unit that cannot be split. Inside a character class, \R matchesthe letter "R".

    Unicode character properties

    To support generic character types there are three additional escape sequences, they are:

    Table 1.6 Generic character types

    Escape Meaning\p{xx} a character with the xx property\P{xx} a character without the xx property

    \X an extended Unicode sequence

    The property names represented by xx above are limited to the Unicode script names, the generalcategory properties, and "Any", which matches any character (including newline). Other properties suchas "InMusicalSymbols" are not currently supported. Note that \P{Any} does not match any characters,so always causes a match failure.

    Sets of Unicode characters are defined as belonging to certain scripts. A character from one of thesesets can be matched using a script name. For example, \p{Greek} or \P{Han}.

    Those that are not part of an identified script are lumped together as "Common". The current list ofscripts is:

    • Arabic

    • Armenian

    • Balinese

    • Bengali

    • Bopomofo

    • Braille

    • Buginese

    12

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    • Buhid

    • Canadian_Aboriginal

    • Cherokee

    • Common

    • Coptic

    • Cuneiform

    • Cypriot

    • Cyrillic

    • Deseret

    • Devanagari

    • Ethiopic

    • Georgian

    • Glagolitic

    • Gothic

    • Greek

    • Gujarati

    • Gurmukhi

    • Han

    • Hangul

    • Hanunoo

    • Hebrew

    • Hiragana

    • Inherited

    • Kannada

    • Katakana

    • Kharoshthi

    • Khmer

    • Lao

    • Latin

    • Limbu

    • Linear_B

    • Malayalam

    • Mongolian

    • Myanmar

    • New_Tai_Lue

    • Nko

    13

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    • Ogham

    • Old_Italic

    • Old_Persian

    • Oriya

    • Osmanya

    • Phags_Pa

    • Phoenician

    • Runic

    • Shavian

    • Sinhala

    • Syloti_Nagri

    • Syriac

    • Tagalog

    • Tagbanwa

    • Tai_Le

    • Tamil

    • Telugu

    • Thaana

    • Thai

    • Tibetan

    • Tifinagh

    • Ugaritic

    • Yi

    Each character has exactly one general category property, specified by a two-letter abbreviation. Forcompatibility with Perl, negation can be specified by including a circumflex between the opening braceand the property name. For example, \p{ˆLu} is the same as \P{Lu}.

    If only one letter is specified with \p or \P, it includes all the general category properties that startwith that letter. In this case, in the absence of negation, the curly brackets in the escape sequence areoptional; these two examples have the same effect:

    \p{L}\pL

    The following general category property codes are supported:The special property L& is also supported: it matches a character that has the Lu, Ll, or Lt property,

    in other words, a letter that is not classified as a modifier or "other".The long synonyms for these properties that Perl supports (such as \ep{Letter}) are not supported

    by GRegex, nor is it permitted to prefix any of these properties with "Is".No character that is in the Unicode table has the Cn (unassigned) property. Instead, this property is

    assumed for any code point that is not in the Unicode table.Specifying caseless matching does not affect these escape sequences. For example, \p{Lu} always

    matches only upper case letters.The \X escape matches any number of Unicode characters that form an extended Unicode sequence.

    \X is equivalent to

    14

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    Table 1.7 Property codes

    Code MeaningC OtherCc ControlCf FormatCn UnassignedCo Private useCs SurrogateL LetterLl Lower case letter

    Lm Modifier letterLo Other letterLt Title case letterLu Upper case letterM MarkMc Spacing markMe Enclosing markMn Non-spacing markN Number

    Nd Decimal numberNl Letter numberNo Other numberP PunctuationPc Connector punctuationPd Dash punctuationPe Close punctuationPf Final punctuationPi Initial punctuationPo Other punctuationPs Open punctuationS SymbolSc Currency symbolSk Modifier symbolSm Mathematical symbolSo Other symbolZ SeparatorZl Line separatorZp Paragraph separatorZs Space separator

    15

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    (?>\PM\pM*)

    That is, it matches a character without the "mark" property, followed by zero or more characters withthe "mark" property, and treats the sequence as an atomic group (see below). Characters with the "mark"property are typically accents that affect the preceding character.

    Matching characters by Unicode property is not fast, because GRegex has to search a structure thatcontains data for over fifteen thousand characters. That is why the traditional escape sequences such as\d and \w do not use Unicode properties.

    Simple assertions

    The final use of backslash is for certain simple assertions. An assertion specifies a condition that has tobe met at a particular point in a match, without consuming any characters from the string. The use ofsubpatterns for more complicated assertions is described below. The backslashed assertions are:

    Table 1.8 Simple assertions

    Escape Meaning\b matches at a word boundary\B matches when not at a word boundary\A matches at the start of the string

    \Z matches at the end of the string or before anewline at the end of the string\z matches only at the end of the string\G matches at first matching position in the string

    These assertions may not appear in character classes (but note that \b has a different meaning,namely the backspace character, inside a character class).

    A word boundary is a position in the string where the current character and the previous characterdo not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of thestring if the first or last character matches \w, respectively.

    The \A, \Z, and \z assertions differ from the traditional circumflex and dollar (described in thenext section) in that they only ever match at the very start and end of the string, whatever options areset. Thus, they are independent of multiline mode. These three assertions are not affected by the G_-REGEX_MATCH_NOTBOL or G_REGEX_MATCH_NOTEOL options, which affect only the behaviour of thecircumflex and dollar metacharacters. However, if the start_position argument of a matching functionis non-zero, indicating that matching is to start at a point other than the beginning of the string, \A cannever match. The difference between \Z and \z is that \Z matches before a newline at the end of thestring as well at the very end, whereas \z matches only at the end.

    The \G assertion is true only when the current matching position is at the start point of the match, asspecified by the start_position argument to the matching functions. It differs from \A when the valueof startoffset is non-zero.

    Note, however, that the interpretation of \G, as the start of the current match, is subtly differentfrom Perl’s, which defines it as the end of the previous match. In Perl, these can be different when thepreviously matched string was empty.

    If all the alternatives of a pattern begin with \G, the expression is anchored to the starting matchposition, and the "anchored" flag is set in the compiled regular expression.

    Circumflex and dollar

    Outside a character class, in the default matching mode, the circumflex character is an assertion thatis true only if the current matching point is at the start of the string. If the start_position argument tothe matching functions is non-zero, circumflex can never match if the G_REGEX_MULTILINE option isunset. Inside a character class, circumflex has an entirely different meaning (see below).

    Circumflex need not be the first character of the pattern if a number of alternatives are involved, butit should be the first thing in each alternative in which it appears if the pattern is ever to match thatbranch. If all possible alternatives start with a circumflex, that is, if the pattern is constrained to matchonly at the start of the string, it is said to be an "anchored" pattern. (There are also other constructs thatcan cause a pattern to be anchored.)

    16

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    A dollar character is an assertion that is true only if the current matching point is at the end of thestring, or immediately before a newline at the end of the string (by default). Dollar need not be the lastcharacter of the pattern if a number of alternatives are involved, but it should be the last item in anybranch in which it appears. Dollar has no special meaning in a character class.

    The meaning of dollar can be changed so that it matches only at the very end of the string, by settingthe G_REGEX_DOLLAR_ENDONLY option at compile time. This does not affect the \Z assertion.

    The meanings of the circumflex and dollar characters are changed if the G_REGEX_MULTILINE op-tion is set. When this is the case, a circumflex matches immediately after internal newlines as well as atthe start of the string. It does not match after a newline that ends the string. A dollar matches before anynewlines in the string, as well as at the very end, when G_REGEX_MULTILINE is set. When newline isspecified as the two-character sequence CRLF, isolated CR and LF characters do not indicate newlines.

    For example, the pattern /ˆabc$/ matches the string "def\nabc" (where \n represents a newline) inmultiline mode, but not otherwise. Consequently, patterns that are anchored in single line mode becauseall branches start with ˆ are not anchored in multiline mode, and a match for circumflex is possible whenthe start_position argument of a matching function is non-zero. The G_REGEX_DOLLAR_ENDONLYoption is ignored if G_REGEX_MULTILINE is set.

    Note that the sequences \A, \Z, and \z can be used to match the start and end of the string in bothmodes, and if all branches of a pattern start with \A it is always anchored, whether or not G_REGEX_-MULTILINE is set.

    Full stop (period, dot)

    Outside a character class, a dot in the pattern matches any one character in the string, including a non-printing character, but not (by default) newline. In UTF-8 a character might be more than one bytelong.

    When a line ending is defined as a single character, dot never matches that character; when thetwo-character sequence CRLF is used, dot does not match CR if it is immediately followed by LF, butotherwise it matches all characters (including isolated CRs and LFs). When any Unicode line endingsare being recognized, dot does not match CR or LF or any of the other line ending characters.

    If the G_REGEX_DOTALL flag is set, dots match newlines as well. The handling of dot is entirelyindependent of the handling of circumflex and dollar, the only relationship being that they both involvenewline characters. Dot has no special meaning in a character class.

    The behaviour of dot with regard to newlines can be changed. If the G_REGEX_DOTALL option is set,a dot matches any one character, without exception. If newline is defined as the two-character sequenceCRLF, it takes two dots to match it.

    The handling of dot is entirely independent of the handling of circumflex and dollar, the only rela-tionship being that they both involve newlines. Dot has no special meaning in a character class.

    Matching a single byte

    Outside a character class, the escape sequence \C matches any one byte, both in and out of UTF-8 mode.Unlike a dot, it always matches any line ending characters. The feature is provided in Perl in order tomatch individual bytes in UTF-8 mode. Because it breaks up UTF-8 characters into individual bytes,what remains in the string may be a malformed UTF-8 string. For this reason, the \C escape sequenceis best avoided.

    GRegex does not allow \C to appear in lookbehind assertions (described below), because in UTF-8mode this would make it impossible to calculate the length of the lookbehind.

    Square brackets and character classes

    An opening square bracket introduces a character class, terminated by a closing square bracket. Aclosing square bracket on its own is not special. If a closing square bracket is required as a member ofthe class, it should be the first data character in the class (after an initial circumflex, if present) or escapedwith a backslash.

    A character class matches a single character in the string. A matched character must be in the set ofcharacters defined by the class, unless the first character in the class definition is a circumflex, in whichcase the string character must not be in the set defined by the class. If a circumflex is actually requiredas a member of the class, ensure it is not the first character, or escape it with a backslash.

    17

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    For example, the character class [aeiou] matches any lower case vowel, while [ˆaeiou] matches anycharacter that is not a lower case vowel. Note that a circumflex is just a convenient notation for spec-ifying the characters that are in the class by enumerating those that are not. A class that starts with acircumflex is not an assertion: it still consumes a character from the string, and therefore it fails if thecurrent pointer is at the end of the string.

    In UTF-8 mode, characters with values greater than 255 can be included in a class as a literal stringof bytes, or by using the \x{ escaping mechanism.

    When caseless matching is set, any letters in a class represent both their upper case and lower caseversions, so for example, a caseless [aeiou] matches "A" as well as "a", and a caseless [ˆaeiou] does notmatch "A", whereas a caseful version would.

    Characters that might indicate line breaks are never treated in any special way when matching char-acter classes, whatever line-ending sequence is in use, and whatever setting of the G_REGEX_DOTALLand G_REGEX_MULTILINE options is used. A class such as [ˆa] always matches one of these characters.

    The minus (hyphen) character can be used to specify a range of characters in a character class. Forexample, [d-m] matches any letter between d and m, inclusive. If a minus character is required in a class,it must be escaped with a backslash or appear in a position where it cannot be interpreted as indicatinga range, typically as the first or last character in the class.

    It is not possible to have the literal character "]" as the end character of a range. A pattern such as[W-]46] is interpreted as a class of two characters ("W" and "-") followed by a literal string "46]", so itwould match "W46]" or "-46]". However, if the "]" is escaped with a backslash it is interpreted as the endof range, so [W-\]46] is interpreted as a class containing a range followed by two other characters. Theoctal or hexadecimal representation of "]" can also be used to end a range.

    Ranges operate in the collating sequence of character values. They can also be used for charactersspecified numerically, for example [\000-\037]. In UTF-8 mode, ranges can include characters whosevalues are greater than 255, for example [\x{100}-\x{2ff}].

    The character types \d, \D, \p, \P, \s, \S, \w, and \W may also appear in a character class, and addthe characters that they match to the class. For example, [\dABCDEF] matches any hexadecimal digit.A circumflex can conveniently be used with the upper case character types to specify a more restrictedset of characters than the matching lower case type. For example, the class [ˆ\W_] matches any letter ordigit, but not underscore.

    The only metacharacters that are recognized in character classes are backslash, hyphen (only whereit can be interpreted as specifying a range), circumflex (only at the start), opening square bracket (onlywhen it can be interpreted as introducing a POSIX class name - see the next section), and the terminatingclosing square bracket. However, escaping other non-alphanumeric characters does no harm.

    Posix character classes

    GRegex supports the POSIX notation for character classes. This uses names enclosed by [: and :] withinthe enclosing square brackets. For example,

    [01[:alpha:]%]

    matches "0", "1", any alphabetic character, or "%". The supported class names areThe "space" characters are HT (9), LF (10), VT (11), FF (12), CR (13), and space (32). Notice that this

    list includes the VT character (code 11). This makes "space" different to \s, which does not include VT(for Perl compatibility).

    The name "word" is a Perl extension, and "blank" is a GNU extension. Another Perl extension isnegation, which is indicated by a ˆ character after the colon. For example,

    [12[:^digit:]]

    matches "1", "2", or any non-digit. GRegex also recognize the POSIX syntax [.ch.] and [=ch=] where"ch" is a "collating element", but these are not supported, and an error is given if they are encountered.

    In UTF-8 mode, characters with values greater than 128 do not match any of the POSIX characterclasses.

    Vertical bar

    Vertical bar characters are used to separate alternative patterns. For example, the pattern

    gilbert|sullivan

    18

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    Table 1.9 Posix classesName Meaningalnum letters and digitsalpha lettersascii character codes 0 - 127

    blank space or tab onlycntrl control charactersdigit decimal digits (same as \d)

    graph printing characters, excluding spacelower lower case lettersprint printing characters, including spacepunct printing characters, excluding letters and digitsspace white space (not quite the same as \s)upper upper case lettersword "word" characters (same as \w)xdigit hexadecimal digits

    matches either "gilbert" or "sullivan". Any number of alternatives may appear, and an empty alter-native is permitted (matching the empty string). The matching process tries each alternative in turn,from left to right, and the first one that succeeds is used. If the alternatives are within a subpattern(defined below), "succeeds" means matching the rest of the main pattern as well as the alternative in thesubpattern.

    Internal option setting

    The settings of the G_REGEX_CASELESS, G_REGEX_MULTILINE, G_REGEX_MULTILINE, and G_REG-EX_EXTENDED options can be changed from within the pattern by a sequence of Perl-style option lettersenclosed between "(?" and ")". The option letters are

    Table 1.10 Option settings

    Option Flagi G_REGEX_CASELESS

    m G_REGEX_MULTILINEs G_REGEX_DOTALLx G_REGEX_EXTENDED

    For example, (?im) sets caseless, multiline matching. It is also possible to unset these options bypreceding the letter with a hyphen, and a combined setting and unsetting such as (?im-sx), which setsG_REGEX_CASELESS and G_REGEX_MULTILINE while unsetting G_REGEX_DOTALL and G_REGEX_-EXTENDED, is also permitted. If a letter appears both before and after the hyphen, the option is unset.

    When an option change occurs at top level (that is, not inside subpattern parentheses), the changeapplies to the remainder of the pattern that follows.

    An option change within a subpattern (see below for a description of subpatterns) affects only thatpart of the current pattern that follows it, so

    (a(?i)b)c

    matches abc and aBc and no other strings (assuming G_REGEX_CASELESS is not used). By thismeans, options can be made to have different settings in different parts of the pattern. Any changesmade in one alternative do carry on into subsequent branches within the same subpattern. For example,

    (a(?i)b|c)

    matches "ab", "aB", "c", and "C", even though when matching "C" the first branch is abandoned beforethe option setting. This is because the effects of option settings happen at compile time. There would besome very weird behaviour otherwise.

    The options G_REGEX_UNGREEDY and G_REGEX_EXTRA and G_REGEX_DUPNAMES can be changedin the same way as the Perl-compatible options by using the characters U, X and J respectively.

    19

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    Subpatterns

    Subpatterns are delimited by parentheses (round brackets), which can be nested. Turning part of apattern into a subpattern does two things:

    • It localizes a set of alternatives. For example, the pattern cat(aract|erpillar|) matches one of thewords "cat", "cataract", or "caterpillar". Without the parentheses, it would match "cataract", "erpil-lar" or an empty string.

    • It sets up the subpattern as a capturing subpattern. This means that, when the whole patternmatches, that portion of the string that matched the subpattern can be obtained using g_regex-_fetch(). Opening parentheses are counted from left to right (starting from 1, as subpattern 0 isthe whole matched string) to obtain numbers for the capturing subpatterns.

    For example, if the string "the red king" is matched against the pattern

    the ((red|white) (king|queen))

    the captured substrings are "red king", "red", and "king", and are numbered 1, 2, and 3, respectively.The fact that plain parentheses fulfil two functions is not always helpful. There are often times

    when a grouping subpattern is required without a capturing requirement. If an opening parenthesis isfollowed by a question mark and a colon, the subpattern does not do any capturing, and is not countedwhen computing the number of any subsequent capturing subpatterns. For example, if the string "thewhite queen" is matched against the pattern

    the ((?:red|white) (king|queen))

    the captured substrings are "white queen" and "queen", and are numbered 1 and 2. The maximumnumber of capturing subpatterns is 65535.

    As a convenient shorthand, if any option settings are required at the start of a non-capturing subpat-tern, the option letters may appear between the "?" and the ":". Thus the two patterns

    (?i:saturday|sunday)(?:(?i)saturday|sunday)

    match exactly the same set of strings. Because alternative branches are tried from left to right, andoptions are not reset until the end of the subpattern is reached, an option setting in one branch doesaffect subsequent branches, so the above patterns match "SUNDAY" as well as "Saturday".

    Named subpatterns

    Identifying capturing parentheses by number is simple, but it can be very hard to keep track of thenumbers in complicated regular expressions. Furthermore, if an expression is modified, the numbersmay change. To help with this difficulty, GRegex supports the naming of subpatterns. A subpattern canbe named in one of three ways: (?...) or (?’name’...) as in Perl, or (?P...) as in Python.References to capturing parentheses from other parts of the pattern, such as backreferences, recursion,and conditions, can be made by name as well as by number.

    Names consist of up to 32 alphanumeric characters and underscores. Named capturing parenthesesare still allocated numbers as well as names, exactly as if the names were not present. By default, aname must be unique within a pattern, but it is possible to relax this constraint by setting the G_REG-EX_DUPNAMES option at compile time. This can be useful for patterns where only one instance of thenamed parentheses can match. Suppose you want to match the name of a weekday, either as a 3-letterabbreviation or as the full name, and in both cases you want to extract the abbreviation. This pattern(ignoring the line breaks) does the job:

    (?Mon|Fri|Sun)(?:day)?|(?Tue)(?:sday)?|(?Wed)(?:nesday)?|(?Thu)(?:rsday)?|(?Sat)(?:urday)?

    There are five capturing substrings, but only one is ever set after a match. The function for extractingthe data by name returns the substring for the first (and in this example, the only) subpattern of that

    20

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    name that matched. This saves searching to find which numbered subpattern it was. If you make areference to a non-unique named subpattern from elsewhere in the pattern, the one that corresponds tothe lowest number is used.

    Repetition

    Repetition is specified by quantifiers, which can follow any of the following items:

    • a literal data character

    • the dot metacharacter

    • the \C escape sequence

    • the \X escape sequence (in UTF-8 mode)

    • the \R escape sequence

    • an escape such as \d that matches a single character

    • a character class

    • a back reference (see next section)

    • a parenthesized subpattern (unless it is an assertion)

    The general repetition quantifier specifies a minimum and maximum number of permitted matches,by giving the two numbers in curly brackets (braces), separated by a comma. The numbers must be lessthan 65536, and the first must be less than or equal to the second. For example:

    z{2,4}

    matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special character. If the secondnumber is omitted, but the comma is present, there is no upper limit; if the second number and thecomma are both omitted, the quantifier specifies an exact number of required matches. Thus

    [aeiou]{3,}

    matches at least 3 successive vowels, but may match many more, while

    \d{8}

    matches exactly 8 digits. An opening curly bracket that appears in a position where a quantifier isnot allowed, or one that does not match the syntax of a quantifier, is taken as a literal character. Forexample, {,6} is not a quantifier, but a literal string of four characters.

    In UTF-8 mode, quantifiers apply to UTF-8 characters rather than to individual bytes. Thus, forexample, \x{100}{2} matches two UTF-8 characters, each of which is represented by a two-byte sequence.Similarly, \X{3} matches three Unicode extended sequences, each of which may be several bytes long(and they may be of different lengths).

    The quantifier {0} is permitted, causing the expression to behave as if the previous item and thequantifier were not present.

    For convenience, the three most common quantifiers have single-character abbreviations:

    Table 1.11 Abbreviations for quantifiers

    Abbreviation Meaning* is equivalent to {0,}+ is equivalent to {1,}? is equivalent to {0,1}

    It is possible to construct infinite loops by following a subpattern that can match no characters witha quantifier that has no upper limit, for example:

    (a?)*

    21

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    Because there are cases where this can be useful, such patterns are accepted, but if any repetition ofthe subpattern does in fact match no characters, the loop is forcibly broken.

    By default, the quantifiers are "greedy", that is, they match as much as possible (up to the maximumnumber of permitted times), without causing the rest of the pattern to fail. The classic example of wherethis gives problems is in trying to match comments in C programs. These appear between /* and */ andwithin the comment, individual * and / characters may appear. An attempt to match C comments byapplying the pattern

    /\*.*\*/

    to the string

    /* first comment */ not comment /* second comment */

    fails, because it matches the entire string owing to the greediness of the .* item.However, if a quantifier is followed by a question mark, it ceases to be greedy, and instead matches

    the minimum number of times possible, so the pattern

    /\*.*?\*/

    does the right thing with the C comments. The meaning of the various quantifiers is not otherwisechanged, just the preferred number of matches. Do not confuse this use of question mark with its use asa quantifier in its own right. Because it has two uses, it can sometimes appear doubled, as in

    \d??\d

    which matches one digit by preference, but can match two if that is the only way the rest of thepattern matches.

    If the G_REGEX_UNGREEDY flag is set, the quantifiers are not greedy by default, but individual onescan be made greedy by following them with a question mark. In other words, it inverts the defaultbehaviour.

    When a parenthesized subpattern is quantified with a minimum repeat count that is greater than 1or with a limited maximum, more memory is required for the compiled pattern, in proportion to thesize of the minimum or maximum.

    If a pattern starts with .* or .{0,} and the G_REGEX_DOTALL flag is set, thus allowing the dot tomatch newlines, the pattern is implicitly anchored, because whatever follows will be tried against everycharacter position in the string, so there is no point in retrying the overall match at any position afterthe first. GRegex normally treats such a pattern as though it were preceded by \A.

    In cases where it is known that the string contains no newlines, it is worth setting G_REGEX_DOTALLin order to obtain this optimization, or alternatively using ˆ to indicate anchoring explicitly.

    However, there is one situation where the optimization cannot be used. When .* is inside capturingparentheses that are the subject of a backreference elsewhere in the pattern, a match at the start may failwhere a later one succeeds. Consider, for example:

    (.*)abc\1

    If the string is "xyz123abc123" the match point is the fourth character. For this reason, such a patternis not implicitly anchored.

    When a capturing subpattern is repeated, the value captured is the substring that matched the finaliteration. For example, after

    (tweedle[dume]{3}\s*)+

    has matched "tweedledum tweedledee" the value of the captured substring is "tweedledee". How-ever, if there are nested capturing subpatterns, the corresponding captured values may have been set inprevious iterations. For example, after

    /(a|(b))+/

    matches "aba" the value of the second captured substring is "b".

    22

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    Atomic grouping and possessive quantifiers

    With both maximizing ("greedy") and minimizing ("ungreedy" or "lazy") repetition, failure of what fol-lows normally causes the repeated item to be re-evaluated to see if a different number of repeats allowsthe rest of the pattern to match. Sometimes it is useful to prevent this, either to change the nature of thematch, or to cause it fail earlier than it otherwise might, when the author of the pattern knows there isno point in carrying on.

    Consider, for example, the pattern \d+foo when applied to the string

    123456bar

    After matching all 6 digits and then failing to match "foo", the normal action of the matcher is to tryagain with only 5 digits matching the \d+ item, and then with 4, and so on, before ultimately failing."Atomic grouping" (a term taken from Jeffrey Friedl’s book) provides the means for specifying that oncea subpattern has matched, it is not to be re-evaluated in this way.

    If we use atomic grouping for the previous example, the matcher give up immediately on failingto match "foo" the first time. The notation is a kind of special parenthesis, starting with (?> as in thisexample:

    (?>\d+)foo

    This kind of parenthesis "locks up" the part of the pattern it contains once it has matched, and afailure further into the pattern is prevented from backtracking into it. Backtracking past it to previousitems, however, works as normal.

    An alternative description is that a subpattern of this type matches the string of characters that anidentical standalone pattern would match, if anchored at the current point in the string.

    Atomic grouping subpatterns are not capturing subpatterns. Simple cases such as the above examplecan be thought of as a maximizing repeat that must swallow everything it can. So, while both \d+ and\d+? are prepared to adjust the number of digits they match in order to make the rest of the patternmatch, (?>\d+) can only match an entire sequence of digits.

    Atomic groups in general can of course contain arbitrarily complicated subpatterns, and can benested. However, when the subpattern for an atomic group is just a single repeated item, as in theexample above, a simpler notation, called a "possessive quantifier" can be used. This consists of an ad-ditional + character following a quantifier. Using this notation, the previous example can be rewrittenas

    \d++foo

    Possessive quantifiers are always greedy; the setting of the G_REGEX_UNGREEDY option is ignored.They are a convenient notation for the simpler forms of atomic group. However, there is no differencein the meaning of a possessive quantifier and the equivalent atomic group, though there may be aperformance difference; possessive quantifiers should be slightly faster.

    The possessive quantifier syntax is an extension to the Perl syntax. It was invented by Jeffrey Friedlin the first edition of his book and then implemented by Mike McCloskey in Sun’s Java package. Itultimately found its way into Perl at release 5.10.

    GRegex has an optimization that automatically "possessifies" certain simple pattern constructs. Forexample, the sequence A+B is treated as A++B because there is no point in backtracking into a sequenceof A’s when B must follow.

    When a pattern contains an unlimited repeat inside a subpattern that can itself be repeated an unlim-ited number of times, the use of an atomic group is the only way to avoid some failing matches taking avery long time indeed. The pattern

    (\D+|)*[!?]

    matches an unlimited number of substrings that either consist of non- digits, or digits enclosed in, followed by either ! or ?. When it matches, it runs quickly. However, if it is applied to

    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    it takes a long time before reporting failure. This is because the string can be divided between theinternal \D+ repeat and the external * repeat in a large number of ways, and all have to be tried. (Theexample uses [!?] rather than a single character at the end, because GRegex has an optimization thatallows for fast failure when a single character is used. It remember the last single character that is

    23

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    required for a match, and fail early if it is not present in the string.) If the pattern is changed so that ituses an atomic group, like this:

    ((?>\D+)|)*[!?]

    sequences of non-digits cannot be broken, and failure happens quickly.

    Back references

    Outside a character class, a backslash followed by a digit greater than 0 (and possibly further digits) isa back reference to a capturing subpattern earlier (that is, to its left) in the pattern, provided there havebeen that many previous capturing left parentheses.

    However, if the decimal number following the backslash is less than 10, it is always taken as a backreference, and causes an error only if there are not that many capturing left parentheses in the entirepattern. In other words, the parentheses that are referenced need not be to the left of the referencefor numbers less than 10. A "forward back reference" of this type can make sense when a repetition isinvolved and the subpattern to the right has participated in an earlier iteration.

    It is not possible to have a numerical "forward back reference" to subpattern whose number is 10 ormore using this syntax because a sequence such as \e50 is interpreted as a character defined in octal.See the subsection entitled "Non-printing characters" above for further details of the handling of digitsfollowing a backslash. There is no such problem when named parentheses are used. A back reference toany subpattern is possible using named parentheses (see below).

    Another way of avoiding the ambiguity inherent in the use of digits following a backslash is touse the \g escape sequence (introduced in Perl 5.10.) This escape must be followed by a positive or anegative number, optionally enclosed in braces.

    A positive number specifies an absolute reference without the ambiguity that is present in the oldersyntax. It is also useful when literal digits follow the reference. A negative number is a relative reference.Consider "(abc(def)ghi)\g{-1}", the sequence \g{-1} is a reference to the most recently started capturingsubpattern before \g, that is, is it equivalent to \2. Similarly, \g{-2} would be equivalent to \1. Theuse of relative references can be helpful in long patterns, and also in patterns that are created by joiningtogether fragments that contain references within themselves.

    A back reference matches whatever actually matched the capturing subpattern in the current string,rather than anything matching the subpattern itself (see "Subpatterns as subroutines" below for a wayof doing that). So the pattern

    (sens|respons)e and \1ibility

    matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility".If caseful matching is in force at the time of the back reference, the case of letters is relevant. For example,

    ((?i)rah)\s+\1

    matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original capturing subpat-tern is matched caselessly.

    Back references to named subpatterns use the Perl syntax \k or \k’name’ or the Pythonsyntax (?P=name). We could rewrite the above example in either of the following ways:

    (?(?i)rah)\s+\k(?P(?i)rah)\s+(?P=p1)

    A subpattern that is referenced by name may appear in the pattern before or after the reference.There may be more than one back reference to the same subpattern. If a subpattern has not actually

    been used in a particular match, any back references to it always fail. For example, the pattern

    (a|(bc))\2

    always fails if it starts to match "a" rather than "bc". Because there may be many capturing parenthe-ses in a pattern, all digits following the backslash are taken as part of a potential back reference number.If the pattern continues with a digit character, some delimiter must be used to terminate the back refer-ence. If the G_REGEX_EXTENDED flag is set, this can be whitespace. Otherwise an empty comment (see"Comments" below) can be used.

    A back reference that occurs inside the parentheses to which it refers fails when the subpattern isfirst used, so, for example, (a\1) never matches. However, such references can be useful inside repeatedsubpatterns. For example, the pattern

    24

  • CHAPTER 1. GLIB OVERVIEW 1.6. REGULAR EXPRESSION SYNTAX

    (a|b\1)+

    matches any number of "a"s and also "aba", "ababbaa" etc. At each iteration of the subpattern, theback reference matches the character string corresponding to the previous iteration. In order for this towork, the pattern must be suc