Skip to content

API Reference

/

Values

Regex

A Regex holds the text of a regular expression for the SurrealDB regex type. SurrealQL regexes use the syntax of the Rust regex crate rather than Python's re module, so the SDK keeps the pattern as text and does not compile it. This page documents the class and when a regex can be sent. Sending a Regex needs SurrealDB 4.0.

Import
from surrealdb import Regex

Source: regex.py

Syntax
Regex(pattern)

Parameter

Type

Description

patternstr

The pattern, in the syntax of the Rust

regex

crate.

A pattern that is not a str raises TypeError. The SDK does not check the syntax, so the server reports a pattern that it cannot read.

Property or methodTypeDescription
patternstrThe pattern, as given.
str(value)strThe same pattern.

Two Regex values are equal when their patterns are equal, and a Regex is hashable.

Pass a Regex as a query variable. In SurrealQL, = between a string and a regex tests whether the string matches. A regex that the server returns reads back as a Regex.

from surrealdb import RecordID, Regex, Surreal

with Surreal("ws://localhost:8000") as db:
    db.signin({"username": "root", "password": "secret"})
    db.use("surrealdb", "docs")

    db.create(RecordID("post", 1), {"title": "News from Bitfinicon"})
    db.create(RecordID("post", 2), {"title": "Other news"})

    sql = "SELECT VALUE id FROM post WHERE title = $pattern"
    pattern = Regex("(?i)bitfinicon")
    print(db.query(sql, {"pattern": pattern}).first())
Output with SurrealDB 4.0
[RecordID(table_name=post, record_id=1)]

Most patterns mean the same in both syntaxes. The Rust syntax has no lookahead, lookbehind or backreferences, so the server refuses a pattern such as a(?=b) that Python's re accepts. To test a pattern with Python's engine as well, compile its text: re.compile(value.pattern).

The SDK refuses a compiled re.Pattern with TypeError, because Python's syntax is not the one the server uses. Wrap the pattern's text in a Regex once it means the same in the Rust syntax.

Servers before 4.0 speak plain cbor, which has no form for a regex, so sending a Regex to one raises ValueError before anything is sent. Send the pattern as a str instead, and cast it in SurrealQL or use string::matches(). Both forms also work on SurrealDB 4.0.

sql = "SELECT VALUE id FROM post WHERE title = <regex> $pattern"
print(db.query(sql, {"pattern": "(?i)bitfinicon"}).first())
Output
[RecordID(table_name=post, record_id=1)]

Was this page helpful?