PCRE2UNICODE(3)
π PCRE2UNICODE(3) π
okay bestie, welcome to the PCRE2UNICODE(3) page, straight out of the Library Functions Manual. this is the part where we talk about how PCRE2 does Unicode, UTF, and all the case-folding chaos that comes with it. buckle up, it's giving β¨extremely detailedβ¨ but i promise it's all worth it.
π NAME π
PCRE2 β Perl-compatible regular expressions (revised API). that's the whole vibe, no cap.
π¦ UNICODE AND UTF SUPPORT π¦
so, PCRE2 is normally built with Unicode support, but lowkey if you don't need it you can build it without it, and then the library is just smaller. your call. π«Ά
when you do have Unicode support, PCRE2 knows about Unicode character properties and can process strings of text in UTF-8, UTF-16, and UTF-32 format (which one depends on the code unit width) β but bestie, this is not the default. unless you specifically ask for it, PCRE2 treats each code unit in a string as one character. yes, really. it's just out here counting code units like it's fine.
there are two ways of telling PCRE2 to switch into UTF mode, where characters may consist of more than one code unit and the range of values is constrained:
- the program can call
pcre2_compile()with thePCRE2_UTFoption, or - the pattern itself may start with the sequence
(*UTF).
but plot twist π β that second one can be locked out by the PCRE2_NEVER_UTF option. meaning: the programmer can stop the supplier of the pattern from switching to UTF mode. main character energy, honestly, protecting their own regex.
heads up: thePCRE2_MATCH_INVALID_UTFoption (peep below for it) forcesPCRE2_UTFto be set. so like, no take-backs.
in UTF mode, both the pattern and any subject strings matched against it are treated as UTF strings instead of strings of individual one-code-unit characters. and there are some other changes to the way characters are handled, all documented below. keep reading, bestie. π
π UNICODE PROPERTY SUPPORT π
when PCRE2 is built with Unicode support, you get to use the escape sequences \p{..}, \P{..}, and \X. and no, this is not dependent on the PCRE2_UTF setting. it's just there. iconic.
the Unicode properties you can test are a subset of the ones Perl supports. currently they're limited to:
- the general category properties, like
Lufor an upper case letter orNdfor a decimal number, - the derived properties
AnyandLc(synonymL&), - the Unicode script names such as
ArabicorHan, Bidi_Class,Bidi_Control,- and a few binary properties.
the full lists live in the pcre2pattern and pcre2syntax documentation, so go peek there for the whole menu. π
in general, only the short names for properties are supported. for example, \p{L} matches a letter β its longer synonym, \p{Letter}, is not supported. nope. π and also, in Perl, many properties may optionally be prefixed by "Is" for compatibility with Perl 5.6. PCRE2 does not support this. sorry babes, that's a Perl thing.
π WIDE CHARACTERS AND UTF MODES π
code points less than 256 can be specified in patterns by either braced or unbraced hexadecimal escape sequences β for example, \x{b3} or \xb3. larger values have to use braced sequences, periodt.
unbraced octal code points up to \777 are also recognized; larger ones can be coded using \o{...}.
the escape sequence \N{U+<hex digits>} is recognized as another way of specifying a Unicode character by code point in a UTF mode. but ngl, it is not allowed in non-UTF mode. vibe check failed, moving on.
in UTF mode, repeat quantifiers apply to complete UTF characters, not to individual code units.
in UTF mode, the dot metacharacter matches one UTF character instead of a single code unit. slay.
in UTF mode, capture group names are not restricted to ASCII, and may contain any Unicode letters and decimal digits, as well as underscore. inclusive king behavior honestly. πΈ
the escape sequence \C can be used to match a single code unit in UTF mode, but π its use can lead to some strange effects because it breaks up multi-unit characters (see the description of \C in the pcre2pattern documentation). for this reason, there is a build-time option that disables support for \C completely. there's also a less draconian compile-time option for locking out the use of \C when a pattern is compiled. choose your fighter.
β οΈ the use of\Cis not supported by the alternative matching functionpcre2_dfa_match()when in UTF-8 or UTF-16 mode, that is, when a character may consist of more than one code unit. using\Cin these modes provokes a match-time error. also, the JIT optimization does not support\Cin these modes. if JIT optimization is requested for a UTF-8 or UTF-16 pattern that contains\C, it will not succeed, and so whenpcre2_match()is called, the matching will be carried out by the interpretive function. so it still works, just... slower. not the flex you wanted. π
the character escapes \b, \B, \d, \D, \s, \S, \w, and \W correctly test characters of any code value, but β and this is the part everyone forgets β by default, the characters that PCRE2 recognizes as digits, spaces, or word characters remain the same set as in non-UTF mode, all with code points less than 256.
this remains true even when PCRE2 is built to include Unicode support, because to do otherwise would slow down matching in many common cases. the performance girlies said no. π
note that this also applies to \b and \B, because they are defined in terms of \w and \W. if you want to test for a wider sense of, say, "digit", you can use explicit Unicode property tests such as \p{Nd}. alternatively, if you set the PCRE2_UCP option, the way that the character escapes work is changed so that Unicode properties are used to determine which characters match, though there are some options that suppress this for individual escapes. for details see the section on generic character types in the pcre2pattern documentation. iykyk. π§
like the escapes, characters that match the POSIX named character classes are all low-valued characters unless the PCRE2_UCP option is set, but there is an option to override this. so you're not stuck.
in contrast to the character escapes and character classes, the special horizontal and vertical white space escapes (\h, \H, \v, and \V) do match all the appropriate Unicode characters, whether or not PCRE2_UCP is set. they said "we're built different" and they meant it. β¨
π UNICODE CASE-EQUIVALENCE π
if either PCRE2_UTF or PCRE2_UCP is set, upper/lower case processing makes use of Unicode properties β except for characters whose code points are less than 128 and that have at most two case-equivalent values. for those, a direct table lookup is used for speed. fast and cute. π
a few Unicode characters, such as Greek sigma, have more than two code points that are case-equivalent, and these are treated specially. special little guys.
setting PCRE2_UCP without PCRE2_UTF allows Unicode-style case processing for non-UTF character encodings such as UCS-2.
there are two ASCII characters (S and K) that, in addition to their ASCII lower case equivalents, have a non-ASCII one as well (long S and Kelvin sign). recognition of these non-ASCII characters as case-equivalent to their ASCII counterparts can be disabled by setting the PCRE2_EXTRA_CASELESS_RESTRICT option. when this is set, all characters in a case equivalence must either be ASCII or non-ASCII; there can be no mixing. strict boundaries, we respect it. π«Ά
Without PCRE2_EXTRA_CASELESS_RESTRICT:
'k' = 'K' = U+212A (Kelvin sign)
's' = 'S' = U+017F (long S)
With PCRE2_EXTRA_CASELESS_RESTRICT:
'k' = 'K'
U+212A (Kelvin sign) only case-equivalent to itself
's' = 'S'
U+017F (long S) only case-equivalent to itself
one language family, Turkish and Azeri, has its own case-insensitivity rules, which can be selected by setting PCRE2_EXTRA_TURKISH_CASING. this alters the behaviour of the 'i', 'I', U+0130 (capital I with dot above), and U+0131 (small dotless i) characters. so specific, so valid.
Without PCRE2_EXTRA_TURKISH_CASING:
'i' = 'I'
U+0130 (capital I with dot above) only case-equivalent to itself
U+0131 (small dotless i) only case-equivalent to itself
With PCRE2_EXTRA_TURKISH_CASING:
'i' = U+0130 (capital I with dot above)
U+0131 (small dotless i) = 'I'
π¨ it is not allowed to specify bothPCRE2_EXTRA_CASELESS_RESTRICTandPCRE2_EXTRA_TURKISH_CASINGtogether. pick one, bestie, you cannot have both.
from release 10.45, the Unicode letter properties Lu (upper case), Ll (lower case), and Lt (title case) are all treated as Lc (cased letter) when caseless matching is set by the PCRE2_CASELESS option or (?i) within the pattern. that's the update, and honestly? it ate. π₯
β¨ SCRIPT RUNS β¨
okay bestie, so the pattern constructs (*script_run:...) and (*atomic_script_run:...), plus their cute synonyms (*sr:...) and (*asr:...), are here to verify that the string matched inside those parentheses is a script run. π In concept, a script run is just a sequence of characters that are all from the same Unicode script. But likeβ¦ it's not that simple, because some scripts are commonly used together, and some diacritical marks and other marks get used with multiple scripts. So the vibe check has layers. β¨
Every Unicode character has a Script property, mostly with a value that corresponds to the name of a script, like Latin, Greek, or Cyrillic. There are also three special values:
"Unknown"β used for code points that have not been assigned, and also for the surrogate code points. In the PCRE2 32-bit library, characters whose code points are greater than the Unicode maximum (U+10FFFF), which are accessible only in non-UTF mode, are assigned the Unknown script."Common"β used for characters that are used with many scripts. These include punctuation, emoji, mathematical, musical, and currency symbols, and the ASCII digits0to9."Inherited"β used for characters such as diacritical marks that modify a previous character. These are considered to take on the script of the character that they modify.
Some Inherited characters are used with many scripts, but many of them are only normally used with a small number of scripts. For example, U+102E0 (Coptic Epact thousands mark) is used only with Arabic and Coptic. In order to make it possible to check this, a Unicode property called Script Extension exists. Its value is a list of scripts that apply to the character. For the majority of characters, the list contains just one script, the same one as the Script property. However, for characters such as U+102E0 more than one Script is listed. There are also some Common characters that have a single, non-Common script in their Script Extension list.
The next section describes the basic rules for deciding whether a given string of characters is a script run. Note, however, that there are some special cases involving the Chinese Han script, and an additional constraint for decimal digits. These are covered in subsequent sections.
πΈ Basic script run rules πΈ
A string that is less than two characters long is a script run. This is the only case in which an Unknown character can be part of a script run. Longer strings are checked using only the Script Extensions property, not the basic Script property.
If a character's Script Extension property is the single value "Inherited", it is always accepted as part of a script run. This is also true for the property "Common", subject to the checking of decimal digits described below. All the remaining characters in a script run must have at least one script in common in their Script Extension lists. In set-theoretic terminology, the intersection of all the sets of scripts must not be empty.
A simple example is an Internet name such as "google.com". The letters are all in the Latin script, and the dot is Common, so this string is a script run. However, the Cyrillic letter "o" looks exactly the same as the Latin "o"; a string that looks the same, but with Cyrillic "o"s is not a script run.
More interesting examples involve characters with more than one script in their Script Extension. Consider the following characters:
U+060C Arabic comma
U+06D4 Arabic full stop
The first has the Script Extension list Arabic, Hanifi Rohingya, Syriac, and Thaana; the second has just Arabic and Hanifi Rohingya. Both of them could appear in script runs of either Arabic or Hanifi Rohingya. The first could also appear in Syriac or Thaana script runs, but the second could not.
π The Chinese Han script π
The Chinese Han script is commonly used in conjunction with other scripts for writing certain languages. Japanese uses the Hiragana and Katakana scripts together with Han; Korean uses Hangul and Han; Taiwanese Mandarin uses Bopomofo and Han. These three combinations are treated as special cases when checking script runs and are, in effect, "virtual scripts". Thus, a script run may contain a mixture of Hiragana, Katakana, and Han, or a mixture of Hangul and Han, or a mixture of Bopomofo and Han, but not, for example, a mixture of Hangul and Bopomofo and Han. PCRE2 (like Perl) follows Unicode's Technical Standard 39 ("Unicode Security Mechanisms", http://unicode.org/reports/tr39/) in allowing such mixtures.
π’ Decimal digits π’
Unicode contains many sets of 10 decimal digits in different scripts, and some scripts (including the Common script) contain more than one set. Some of these decimal digits are visually indistinguishable from the common ASCII digits. In addition to the script checking described above, if a script run contains any decimal digits, they must all come from the same set of 10 adjacent characters.
β¨ VALIDITY OF UTF STRINGS β¨
ok so when PCRE2_UTF is set, the strings you pass in as patterns and subjects get vibe-checked for validity on entry to the relevant functions β that's the default behaviour, bestie, no skipping. If an invalid UTF string shows up, you get a negative error code back. And the code unit offset pointing at the offending character can be pulled out of the match data block by calling pcre2_get_startchar() β that's literally what it's for, and it's what you use after a UTF error.
Now sometimes you already know your strings are valid and you just wanna skip those checks to go faster β say, a long subject string that's getting scanned over and over. In that case, set PCRE2_NO_UTF_CHECK at compile time or at match time, and PCRE2 will assume that the pattern or subject it's given (respectively, babe, respectively) contains only valid UTF code unit sequences.
π HARD WARNING, NO CAP: if you pass an invalid UTF string whilePCRE2_NO_UTF_CHECKis set, the result is undefined β your program may crash, loop forever, or just hand you straight-up incorrect results. There is, however, one mode of matching that can handle invalid UTF subject strings. It's enabled by passingPCRE2_MATCH_INVALID_UTFtopcre2_compile()and it gets its own section right below. The rest of this section is about the case wherePCRE2_MATCH_INVALID_UTFis not set.
Also, sneaky detail: passing PCRE2_NO_UTF_CHECK to pcre2_compile() only disables the UTF check for the pattern. It does not carry over to subject strings. If you want the check disabled for a subject string, you have to pass that same option to pcre2_match() or pcre2_dfa_match(). Two separate vibes, two separate options, don't get it twisted π«Ά
UTF-16 and UTF-32 strings can flag their endianness with a special code known as a byte-order mark (BOM). The PCRE2 functions do not handle this β they expect strings to be in host byte order. Periodt.
Unless PCRE2_NO_UTF_CHECK is set, a UTF string gets checked before any other processing takes place. For pcre2_match() and pcre2_dfa_match() calls with a non-zero starting offset, the check only applies to that part of the subject that could be inspected during matching, plus there's a check that the starting offset points to the first code unit of a character or to the end of the subject. If there are no lookbehind assertions in the pattern, the check starts at the starting offset. Otherwise it starts at the length of the longest lookbehind before the starting offset β or at the start of the subject, if there aren't that many characters before the starting offset. And heads up: the sequences \b and \B are one-character lookbehinds. π
On top of checking the format of the string, there's a check that all code points lie in the range U+0 to U+10FFFF, excluding the surrogate area. The so-called "non-character" code points are not excluded, because Unicode corrigendum #9 makes it clear that they shouldn't be. (Iconic of corrigendum #9 honestly.)
Characters in the "Surrogate Area" of Unicode are reserved for use by UTF-16, where they show up in pairs to encode code points with values greater than 0xFFFF. The code points that get encoded by UTF-16 pairs are available independently in the UTF-8 and UTF-32 encodings. (In other words, the whole surrogate thing is a fudge for UTF-16 which unfortunately messes up UTF-8 and UTF-32. We don't make the rules π)
Setting PCRE2_NO_UTF_CHECK at compile time does not disable the error you get if an escape sequence for an invalid Unicode code point is encountered in the pattern. If you want to allow escape sequences such as \x{d800} (a surrogate code point), you can set the PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES extra option. But that's only possible in UTF-8 and UTF-32 modes, because these values are not representable in UTF-16. π
π¨ Errors in UTF-8 strings
The following negative error codes are given for invalid UTF-8 strings:
PCRE2_ERROR_UTF8_ERR1PCRE2_ERROR_UTF8_ERR2PCRE2_ERROR_UTF8_ERR3PCRE2_ERROR_UTF8_ERR4PCRE2_ERROR_UTF8_ERR5
The string ends with a truncated UTF-8 character; the code specifies how many bytes are missing (1 to 5). Although RFC 3629 restricts UTF-8 characters to be no longer than 4 bytes, the encoding scheme (originally defined by RFC 2279) allows for up to 6 bytes, and this is checked first; hence the possibility of 4 or 5 missing bytes.
PCRE2_ERROR_UTF8_ERR6PCRE2_ERROR_UTF8_ERR7PCRE2_ERROR_UTF8_ERR8PCRE2_ERROR_UTF8_ERR9PCRE2_ERROR_UTF8_ERR10
The two most significant bits of the 2nd, 3rd, 4th, 5th, or 6th byte of the character do not have the binary value 0b10 (that is, either the most significant bit is 0, or the next bit is 1).
PCRE2_ERROR_UTF8_ERR11PCRE2_ERROR_UTF8_ERR12
A character that is valid by the RFC 2279 rules is either 5 or 6 bytes long; these code points are excluded by RFC 3629.
PCRE2_ERROR_UTF8_ERR13
A 4-byte character has a value greater than 0x10ffff; these code points are excluded by RFC 3629.
PCRE2_ERROR_UTF8_ERR14
A 3-byte character has a value in the range 0xd800 to 0xdfff; this range of code points are reserved by RFC 3629 for use with UTF-16, and so are excluded from UTF-8.
PCRE2_ERROR_UTF8_ERR15PCRE2_ERROR_UTF8_ERR16PCRE2_ERROR_UTF8_ERR17PCRE2_ERROR_UTF8_ERR18PCRE2_ERROR_UTF8_ERR19
A 2-, 3-, 4-, 5-, or 6-byte character is "overlong", that is, it codes for a value that can be represented by fewer bytes, which is invalid. For example, the two bytes 0xc0, 0xae give the value 0x2e, whose correct coding uses just one byte.
PCRE2_ERROR_UTF8_ERR20
The two most significant bits of the first byte of a character have the binary value 0b10 (that is, the most significant bit is 1 and the second is 0). Such a byte can only validly occur as the second or subsequent byte of a multi-byte character.
PCRE2_ERROR_UTF8_ERR21
The first byte of a character has the value 0xfe or 0xff. These values can never occur in a valid UTF-8 string.
π¨ Errors in UTF-16 strings
The following negative error codes are given for invalid UTF-16 strings:
PCRE2_ERROR_UTF16_ERR1β Missing low surrogate at end of stringPCRE2_ERROR_UTF16_ERR2β Invalid low surrogate follows high surrogatePCRE2_ERROR_UTF16_ERR3β Isolated low surrogate
π¨ Errors in UTF-32 strings
The following negative error codes are given for invalid UTF-32 strings:
PCRE2_ERROR_UTF32_ERR1β Surrogate character (0xd800to0xdfff)PCRE2_ERROR_UTF32_ERR2β Code point is greater than0x10ffff
π MATCHING IN INVALID UTF STRINGS π
ok so you can run pattern matches on subject strings that might contain invalid UTF sequences β you just have to call pcre2_compile() with the PCRE2_MATCH_INVALID_UTF option. This is supported by pcre2_match(), including JIT matching, but not by pcre2_dfa_match(). When PCRE2_MATCH_INVALID_UTF is set, it forces PCRE2_UTF to be set as well. Note, however, that the pattern itself must still be a valid UTF string. β¨
If you do not set PCRE2_MATCH_INVALID_UTF when calling pcre2_compile, and you're not certain that your subject strings are valid UTF sequences, you should not make use of the JIT "fast path" function pcre2_jit_match(), because it bypasses sanity checks β including the one for UTF validity. An invalid string may cause undefined behaviour, including looping, crashing, or giving the wrong answer.
π bestie, that's the "we don't check, we just go" function and you do not want that energy with garbage input. undefined behaviour is not a vibe.
Setting PCRE2_MATCH_INVALID_UTF does not affect what pcre2_compile() generates, but if pcre2_jit_compile() is subsequently called, it does generate different code. If JIT isn't used, the option affects the behaviour of the interpretive code in pcre2_match(). When PCRE2_MATCH_INVALID_UTF is set at compile time, PCRE2_NO_UTF_CHECK is ignored at match time.
In this mode, an invalid code unit sequence in the subject never matches any pattern item. It does not match dot, it does not match \p{Any}, it does not even match negative items such as [^X]. A lookbehind assertion fails if it encounters an invalid sequence while moving the current point backwards. In other words, an invalid UTF code unit sequence acts as a barrier which no match can cross. π§
You can also think of this as the subject being split up into fragments of valid UTF, delimited internally by invalid code unit sequences. The pattern is matched fragment by fragment. The result of a successful match, however, is given as code unit offsets in the entire subject string in the usual way. There are a few points to consider:
- The internal boundaries are not interpreted as the beginnings or ends of lines and so do not match circumflex or dollar characters in the pattern.
- If
pcre2_match()is called with an offset that points to an invalid UTF-sequence, that sequence is skipped, and the match starts at the next valid UTF character, or the end of the subject. - At internal fragment boundaries,
\band\Bbehave in the same way as at the beginning and end of the subject. For example, a sequence such as\bWORD\bwould match an instance ofWORDthat is surrounded by invalid UTF code units.
Using PCRE2_MATCH_INVALID_UTF, an application can run matches on arbitrary data, knowing that any matched strings that are returned are valid UTF. This can be useful when searching for UTF text in executable or other binary files. π₯
Note, however, that the 16-bit and 32-bit PCRE2 libraries process strings as sequences of uint16_t or uint32_t code points. They cannot find valid UTF sequences within an arbitrary string of bytes unless such sequences are suitably aligned. (Alignment really said "it's giving main character" and honestly, fair.)
π AUTHOR π
Philip Hazel Retired from University Computing Service Cambridge, England.
π REVISION π
Last updated: 27 November 2024 Copyright (c) 1997-2024 University of Cambridge.
and that's a wrap on the whole thing, bestie!! π this was PCRE2UNICODE(3) from the PCRE2 10.49 era, dated 27 November 2024 β genuinely iconic documentation, no notes, we ate π
β¨π¦
π¦ where this page comes from
- alpine 3.23: pcre2-doc 10.49-r0 Β· BSD-3-Clause
- alpine 3.24: pcre2-doc 10.49-r0 Β· BSD-3-Clause
- arch rolling: pcre2 10.49-1 Β· BSD-2-Clause AND BSD-3-Clause WITH PCRE2-exception
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms