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.
from surrealdb import RegexSource: regex.py
Constructor
Regex(pattern)Parameter | Type | Description |
|---|---|---|
pattern | str | The pattern, in the syntax of the Rust regexcrate. |
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 method | Type | Description |
|---|---|---|
pattern | str | The pattern, as given. |
str(value) | str | The same pattern. |
Two Regex values are equal when their patterns are equal, and a Regex is hashable.
Matching in a query
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())[RecordID(table_name=post, record_id=1)] Rust syntax and Python's re
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 SurrealDB 4.0
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())[RecordID(table_name=post, record_id=1)]See also
Python values for every value class
Regex in SurrealQL
string::matches()for matching with a pattern given as a string