Regular expression

Searching text with patterns, in PCRE syntax, as PureBasic does.

PureBasic uses the PCRE library. x has an engine of its own, written in x, that follows PCRE's syntax and rules: the first alternative that works wins (a|ab finds a), and * + ? take as much as they can unless followed by ?. Behaviour PCRE leaves to the program (group positions, empty matches, flag values) was checked against PureBasic 6.50.

The engine doesn't backtrack catastrophically. When a search takes long, it starts remembering which choices have already failed at which position, and never tries them again. So patterns like (a|aa)*b, ((a|aa)*)*b or (x+x+)+y, which can take PCRE minutes on a long string, take time in proportion to the length of the text. Look-arounds and atomic groups are covered too.

The exception is a pattern with back references (\1), where earlier choices change what can match later. Like PCRE, such a search gives up after 10 million steps and reports no match.

A pattern compiles to at most 2 million instructions; a larger one (such as (a{60000}){60000}) fails with regular expression is too large. A list of 50,000 words separated by | fits.

Text is handled as UTF-16 units, the way x keeps strings. A character outside the Basic Multilingual Plane (an emoji, say) counts as two characters, and . matches each half.

Patterns

Syntax Meaning
x the character x; \ before any character that isn't a letter or digit takes it literally
. any character except a newline (any at all with DotAll)
[abc] [a-z] [^abc] one character from a set, or not from it; \d \w \s and [:alpha:] can be used inside
\d \w \s \h a digit, a word character (a-z A-Z 0-9 _), white space, horizontal space; \D \W \S \H the opposite
[:alpha:] and the like inside a set: alpha digit alnum upper lower space blank word xdigit punct cntrl print graph
\t \n \r \f \e \a \0 \xhh \x{hhhh} \cX control and other characters by code
\Q...\E the text between taken literally
^ $ the start and end of the text; with MultiLine, of each line. $ also matches before a newline at the very end
\A \z \Z the start, the end, the end or before a final newline (whatever the flags)
\b \B a word boundary, or not one
x* x+ x? x{n} x{n,} x{n,m} repeats, as many as possible
x*? x+? ... repeats, as few as possible
x*+ x++ ... possessive: as many as possible, and never fewer
a\|b either
(...) a group, numbered from 1
(?<name>...) (?'name'...) (?P<name>...) a named group (it is numbered too)
(?:...) a group that isn't captured
(?>...) an atomic group: once matched, never tried another way
(?=...) (?!...) followed by, not followed by
(?<=...) (?<!...) preceded by, not preceded by (the inside must have a fixed length)
\1 ... \99, \g{1}, \g{-1}, \k<name>, (?P=name) a back reference: the same text as a group matched
(?i) (?m) (?s) (?x), (?-i), (?i:...) switch NoCase, MultiLine, DotAll, Extended on or off from there, or inside a group
(?#...) a comment

CreateRegularExpression fails, and RegularExpressionError() says why, for any of these PCRE features that x doesn't have:

  • Unicode properties: \p \P \X.
  • Recursion: (?R) (?1).
  • Conditions: (?(1)...).
  • \G, \K and \R.
  • (?|...) and (*VERB).
  • A look-behind whose alternatives differ in length, like (?<=ab|c).
  • A named back reference that comes before its group.

Flags

Constant Value
#PB_RegularExpression_DotAll 32 . matches newlines too
#PB_RegularExpression_Extended 128 white space in the pattern is ignored, and # starts a comment
#PB_RegularExpression_MultiLine 1024 ^ and $ match at each line
#PB_RegularExpression_AnyNewLine $10000000 CR, LF and CR LF are all newlines (otherwise only LF)
#PB_RegularExpression_NoCase 8 upper and lower case match each other, for any letter the system knows (É and é too)

CreateRegularExpression ✅

Result = CreateRegularExpression(#RegularExpression, Pattern$ [, Flags])

Compiles Pattern$. Returns non-zero, or 0 if the pattern has an error (see RegularExpressionError). With #PB_Any it returns the new number.

FreeRegularExpression, IsRegularExpression ✅

FreeRegularExpression(#RegularExpression)
Result = IsRegularExpression(#RegularExpression)

FreeRegularExpression(#PB_All) frees them all.

RegularExpressionError ✅

Text$ = RegularExpressionError()

Returns why the last CreateRegularExpression failed, such as missing closing parenthesis.

MatchRegularExpression ✅

Result = MatchRegularExpression(#RegularExpression, String$)

Returns non-zero if the pattern matches anywhere in String$.

ExtractRegularExpression ✅

Result = ExtractRegularExpression(#RegularExpression, String$, Array$())

Puts every match into Array$(), which is resized to hold them, and returns how many there are.

ReplaceRegularExpression ✅

Result$ = ReplaceRegularExpression(#RegularExpression, String$, ReplaceString$)

Returns String$ with every match replaced by ReplaceString$. As in PureBasic, ReplaceString$ is used as it is: \1 is just those two characters. ReplaceRegularExpressionGroups puts the groups in.

OpenConsole()
CreateRegularExpression(0, "\d+")
Dim found$(0)
n = ExtractRegularExpression(0, "3 apples, 12 pears and 7 figs", found$())
For i = 0 To n - 1
  PrintN(found$(i))
Next
PrintN(ReplaceRegularExpression(0, "3 apples, 12 pears", "some"))
CreateRegularExpression(1, "^colou?r$", #PB_RegularExpression_NoCase)
PrintN(Str(MatchRegularExpression(1, "Colour")) + Str(MatchRegularExpression(1, "colr")))

Output:

3
12
7
some apples, some pears
10

ExamineRegularExpression, NextRegularExpressionMatch ✅

Result = ExamineRegularExpression(#RegularExpression, String$)
Result = NextRegularExpressionMatch(#RegularExpression)

ExamineRegularExpression starts going through the matches in String$. Each NextRegularExpressionMatch moves to the next one, and returns 0 when there are no more. After an empty match, the next match may start at the same place but must not be empty there. For example, a* in baab matches at 1 (empty), 2 (aa), 4 and 5.

The current match ✅

Text$ = RegularExpressionMatchString(#RegularExpression)
Position = RegularExpressionMatchPosition(#RegularExpression)
Length = RegularExpressionMatchLength(#RegularExpression)
Count = CountRegularExpressionGroups(#RegularExpression)
Text$ = RegularExpressionGroup(#RegularExpression, Group)
Position = RegularExpressionGroupPosition(#RegularExpression, Group)
Length = RegularExpressionGroupLength(#RegularExpression, Group)
Text$ = RegularExpressionNamedGroup(#RegularExpression, Name$)
Position = RegularExpressionNamedGroupPosition(#RegularExpression, Name$)
Length = RegularExpressionNamedGroupLength(#RegularExpression, Name$)

The match's position counts from 1 at the start of the string. As in PureBasic, a group's position counts from 1 at the start of the match. A group that took no part in the match gives "", position 0 and length 0. Groups are numbered from 1 in the order their ( appear, named groups included. Names are case sensitive.

OpenConsole()
CreateRegularExpression(0, "(?<key>\w+)=(?<value>\d+)")
ExamineRegularExpression(0, "width=640, height=480, depth")
While NextRegularExpressionMatch(0)
  PrintN(RegularExpressionNamedGroup(0, "key") + " is " + RegularExpressionGroup(0, 2) + " (at " + Str(RegularExpressionMatchPosition(0)) + ", value at +" + Str(RegularExpressionGroupPosition(0, 2) - 1) + ")")
Wend

Output:

width is 640 (at 1, value at +6)
height is 480 (at 12, value at +7)

x additions

These are not in PureBasic. A program's own procedure with one of these names is used instead.

ReplaceRegularExpressionGroups

Result$ = ReplaceRegularExpressionGroups(#RegularExpression, String$, ReplaceString$)

Like ReplaceRegularExpression, except that in ReplaceString$:

  • \0 stands for the whole match;
  • \1 to \99 stand for a group;
  • \k<name> stands for a named group;
  • \\ is a backslash.

SplitRegularExpression

Count = SplitRegularExpression(#RegularExpression, String$, Array$())

Splits String$ at each match. The pieces go into Array$(), which is resized to hold them, and returns how many there are. An empty match at the very start or end of the string doesn't split, so splitting "abc" on x* gives a, b and c.

EscapeRegularExpression

Pattern$ = EscapeRegularExpression(Text$)

Returns a pattern that matches Text$ literally: every character with a meaning in a pattern gets a \.

OpenConsole()
CreateRegularExpression(0, "(\d{4})-(\d\d)-(\d\d)")
PrintN(ReplaceRegularExpressionGroups(0, "due 2026-12-24", "\3/\2/\1"))
CreateRegularExpression(1, "\s*[,;]\s*")
Dim part$(0)
n = SplitRegularExpression(1, "red, green ;blue,  yellow", part$())
For i = 0 To n - 1
  Print("<" + part$(i) + "> ")
Next
PrintN("")
CreateRegularExpression(2, EscapeRegularExpression("$3.50 (each)"))
PrintN(Str(MatchRegularExpression(2, "price: $3.50 (each)")))

Output:

due 24/12/2026
<red> <green> <blue> <yellow> 
1