Regex guardrail
The regex guardrail is a Tier 1 (in-process, sub-millisecond for typical content) guardrail that scans request and response content against named pattern libraries or custom expressions. It is the recommended starting point for detecting structured sensitive data such as personally identifiable information (PII), payment card numbers, credentials, and healthcare identifiers.
The built-in email, jwt, cvv and mrn patterns scan in time linear in the size of the content, also on hostile input such as a long run of letters, a long run of whitespace or a base64-encoded image body. A single large prompt cannot make these patterns consume quadratic CPU.
Custom patterns are Lua patterns, and their cost depends on their shape. A pattern with adjacent or nested repetitions over the same characters, for example %w+@%w+%.%w+, can take time that grows with the square of a long run of matching characters, such as base64 image data. Start a custom pattern with a short literal prefix that is rare in your content and is not made of characters the following repetition also matches (a prefix such as ey followed by [%w_-]+ still takes quadratic time on a long run), use bounded repetitions (for example %w%w?%w? or a fixed maximum length) instead of open-ended + and *, and test it against large sample text in the Guardrail Builder before enabling it.
Regex guardrail editor
⚠️ Caution: A regex guardrail with no
patternsand nocustom_patternsmatches nothing — it is stored and listed, but the gateway returnspassfor it on every request. Apatternsentry that is not a known pattern or set name is silently ignored, so a typo (credit_cardforcc) leaves a non-empty list unable to fire.GET /admin/v1/gateways/<ID>/detectorsreports such a detector asactive: falsewithinactive_reason: "no_patterns", and the Guardrail Builder badges it No patterns.
When to use the regex guardrail
Use the regex guardrail when you need fast, deterministic matching of structured data formats. It adds no latency overhead. For unstructured PII detection — such as names, dates, or addresses expressed in natural language — use the NLP PII Detector (Tier 2) instead.
How it works
The guardrail evaluates the patterns array (named patterns) and the custom_patterns array (raw Lua-pattern strings) against the inspected body. Both lists are evaluated together. A single match from either list triggers the configured action.
For action: "scrub", each matched span is replaced with the scrub_placeholder value, inserted literally (a % in it has no special meaning — a placeholder written for the old behaviour with %% now shows %%; write a single %). Matches that overlap or touch are merged into one placeholder wherever the text is read per JSON level (request messages and tool-call arguments, a JSON response and the values inside it, tool results written as JSON): a pattern for ab and one for cd over abcd give one placeholder there. In text that is read only as written (a plain-text response, a request body that cannot be decoded) separate matches keep separate placeholders, even when they touch, and only overlapping matches merge. For the checksum patterns (cc, routing_number) block / flag now check every candidate — the same candidates scrub checks — so a number that fails the checksum no longer hides a valid card later in the text (before, only the first candidate was checked). An empty match (a pattern such as x* that can match nothing) is never a match. Every pattern is matched against the original text (never against another pattern's placeholder), so a pattern that relies on a word or digit boundary does not match where that boundary would only appear after another pattern's replacement (for example two numbers written together without a separator). The replacement is permanent — nothing restores the original value in the answer or in the stored conversation (see Verdicts); use the PII Protector guardrail when the model's answer needs to reference the real values.
Agent runs and match location. On an agent run, the system blocks the gateway writes itself are not scanned. A request-phase block names where it matched (where: system:instructions, user, tool_result:<tool>, fetched:<host>), never the matched value. Both work exactly as for the keyword guardrail: see Keyword guardrail: agent runs and Match location.
On the request phase block and flag read the same decoded content as the scrub: each JSON level is read decoded (see How escapes are read), and every string value that is itself a JSON document (a tool call's arguments, a tool result written as JSON) as a document of its own, at every decoding level (at most 64 decoding steps; deeper is refused rather than passed unchecked). A match hidden behind an escape such as \u00fc inside earlier tool-call arguments therefore triggers block and flag exactly as it triggers the scrub. On an earlier turn of the conversation, block masks the matching span with the placeholder instead of refusing the whole request; a match in the newest user message is refused. A match that lies wholly inside an occurrence of the detector's own placeholder is not a match (so an earlier turn the gateway already masked is not refused again), unless the placeholder itself consists only of a match of the detector (for example the keyword is secret and the placeholder is secret): then the placeholder is not exempt and a text holding it fires block and flag like any other match. A placeholder that contains a quote or a backslash is not recognised as the placeholder by block and flag, so its words count as a match there.
Text the gateway's own protection controls write into a request is never a match for this detector: the placeholder that replaces a removed earlier turn ([earlier message removed by guardrail policy]), the text a keyword or regex scrub guardrail inserts (for example [REDACTED]), the <TYPE> masks the gateway writes for the entity types it knows (the NLP PII Detector; the mask of an unknown type is read as ordinary text), and the protection tokens that the PII Protector and the Custom PII detector issue. The same words anywhere else in the user's text still match; only an exact copy of the gateway's own text is treated as gateway text. A match that lies wholly inside that text is ignored; a match that extends beyond it, across its edge, is a match like any other. Other texts the gateway adds to tool output, such as the notices that stand in for withheld tool results, files, documents and web-search queries, are checked like any tool output: in an earlier turn a match there is masked and the conversation continues, and in the newest turn it is refused. The exemption does not apply when a pattern (an anchored pattern included) matches the whole of that text (for example a pattern %[[^%]]+%] against the placeholder [REDACTED], which it covers in full): that text is then not exempt, and a request in which the gateway had to remove an earlier turn is refused rather than passed. Tool-call arguments the gateway empties to {} when it removes an earlier turn are not exempt: a pattern that matches {} refuses such a request.
On the request phase the scrub also covers the conversation history the request carries — earlier messages, earlier tool results and the arguments of earlier tool calls included. Each JSON level is read decoded (see How escapes are read), and every string value that is itself a JSON document (a tool call's arguments, a tool result written as JSON) is decoded and matched as a document of its own, so a tool call's arguments stay valid JSON after masking. A match that runs from a field name into its value (for example password%W+%w+ over {"password":"…"}) masks the value; the field name and the JSON syntax around it stay as written. A match hidden behind an escape inside a value (for example \u00fc for ü) is found and masked as well. A match in a key or a number inside tool-call arguments, or one that covers only JSON syntax there, cannot be masked without changing the call, so the request is blocked instead. A match the gateway cannot mask in place — inside a document that is encoded as a string more than once, inside a document nested deeper than the gateway reads, or visible only after further decoding of a value (at most 64 decoding steps; deeper is refused rather than passed unchecked) — blocks the request (scrub_uncommittable) and the body is left unchanged. A match in a field name of the request itself is kept and recorded as "scrub not applied", also when other values were masked. When nothing could be masked the detector reports pass and the request is marked scrub_uncommittable. Text that already holds the scrub placeholder (an earlier turn the client sends again) is not masked a second time. A scrub whose placeholder consists only of a match of the detector cannot be applied: the request is blocked (scrub_uncommittable), and on the response phase the answer is withheld.
How escapes are read
Escapes are read the same way on the request, the response and tool results, for block, flag and scrub alike; the rules are described once under How escapes are read. For this detector, patterns see the decoded text (%s matches a line break, and a match that a provider spells with \uXXXX in a response is found), except anchored patterns (^, $): those are matched against the body as written, never per decoded level. A request scrub ignores them; block and flag on the request match them as written; the response matches them as written for every action. On tool results anchored patterns are not applied.
Configuration reference
| Field | Type | Default | Description |
|---|---|---|---|
type |
string | — | Must be "regex" |
name |
string | — | Human-readable label for this guardrail instance |
action |
string | "flag" |
What to do on a match: block, scrub, or flag. Any other value is treated as flag. A new card in the Guardrail Builder starts with block. |
target |
string | "request" |
Which traffic to inspect: request, response, or both |
patterns |
array | [] |
Named patterns or pattern sets to match (see tables below) |
custom_patterns |
array | [] |
Raw Lua-pattern strings to match in addition to named patterns |
scrub_placeholder |
string | "[REDACTED]" |
Replacement text used when action is "scrub" |
Named patterns
Reference these by name in the patterns array. The false positive (FP) rates come from the gateway's false-positive benchmark on a set of 200 hand-written business prompts. On the general-purpose corpora of the same benchmark (OR-Bench-hard, XSTest, a Dolly sample) the false-positive rate of every pattern stays near zero.
| Name | Description | FP risk |
|---|---|---|
email |
Email addresses | Medium — 8% FP on business text |
phone |
Phone numbers: an optional +, a digit and at least nine more digits, spaces, brackets or hyphens |
High — 26% FP; phone numbers appear in everyday queries |
ssn |
US Social Security Numbers (dashes optional) | High — 11.5% FP; 9-digit sequences match SSN format |
dob |
Dates of birth (MM/DD/YYYY or MM-DD-YYYY; the / form matches since October 2026) |
Low — 0% FP |
ip_address |
IPv4 addresses | High — 13% FP; IP addresses appear in technical text |
cc |
Credit/debit card numbers (Luhn-validated) | Low — 2.5% FP (Luhn check eliminates most false matches) |
cvv |
Card security codes after a CV, CVV, CVV2, CVC, CVC2 or CV2 label (any case, optional :), 3 or 4 digits (the CVV2 and CVC forms match since November 2026; a bare CV 123 also matches). CID and CAV2 labels are not covered; use a custom pattern for them |
Low — 0% FP. A CVC label followed by 3 to 4 digits in non-card text (for example the fabric CVC 220) also matches |
card_expiry |
Card expiry dates (12/25, 12-25; the / form matches since October 2026) |
Low — 1.5% FP |
iban |
International Bank Account Numbers (upper-case country code) | Low — 0% FP |
routing_number |
ABA routing numbers (9 digits, ABA checksum-validated) | Medium — 5% FP; 9-digit numbers are common |
mrn |
Medical Record Numbers after an MRN label (5 to 8 digits) |
Low — 0% FP |
npi |
National Provider Identifiers (10 digits) | Low — 0.5% FP |
national_id |
National ID numbers: an upper-case letter, 8 digits, an upper-case letter | Low — 0% FP |
passport_number |
Passport numbers: 1 or 2 upper-case letters followed by 7 digits | Low — 0% FP |
api_key |
An api_key / api-key / apikey label followed by = or : and at least 16 key characters |
Low — 0% FP |
jwt |
JSON Web Tokens (ey... three-segment format) | Low — 0% FP |
💡 Note:
phone,ssn, andip_addresshave high false positive rates on general business text (see the table above). Useaction: scrubrather thanaction: blockfor these patterns, or switch to the NLP PII Detector, which applies NLP context to reduce false detections.💡 Note: The
ccpattern applies a Luhn checksum check in addition to format matching. This significantly reduces false positives from 16-digit numbers that happen to match a card number format but are not valid card numbers.Limit: a valid card number written directly after another 4-digit group (
PIN 1234 4111 1111 1111 1111) is not matched — the first 16 digits form an invalid candidate and the search continues after them. Re-checking the card that ends such a digit run would catch it, but on lists of 4-digit numbers it nearly doubles the flagged lines (measured: about 10 % → 18 %), so it is not done. Separate the number from the card (a comma or a word between them) and it matches.💡 Tool results: with
action: "scrub"or"block"the detector also runs on tool results returned to the model — see PII Protector — Which detectors cover tool results. How a JSON tool result is read, masked or withheld is described once under How escapes are read.⚠️
/in a pattern (changed October 2026). The detector matches the request as JSON text, and the JSON encoder used to write/as\/— sodob(01/02/1990),card_expiry(12/25) and any custom pattern or keyword containing/never matched. They now match. A gateway usingdob,card_expiry,pci_panorhipaa_structuredwithaction: "block"may therefore start blocking prompts that contain such dates (withscrub: masking them). The same applies on the response phase for a JSON response. Conversely, a custom pattern written to match the escaped form (\\/) no longer matches — write/.
Pattern sets
Pattern sets are shorthand aliases that expand to multiple named patterns. Use them in the patterns array the same way as individual pattern names.
| Set | Patterns included | FP risk |
|---|---|---|
pci_pan |
cc, cvv, card_expiry, iban, routing_number |
Medium — 9% FP; most false positives come from 9-digit numbers that pass the routing_number checksum |
hipaa_structured |
ssn, mrn, npi, dob, phone, email, ip_address |
High — 50.5% FP; driven by phone, ssn and ip_address, which match much general text |
gdpr_structured |
email, phone, ip_address, iban, national_id, passport_number |
High — 47% FP; driven by phone and ip_address |
credentials |
api_key, jwt |
Low — 0% FP; format-specific |
pii_basic |
email, phone, ssn |
High — 37.5% FP; driven by phone and ssn |
💡 Note:
hipaa_structured,gdpr_structured, andpii_basicall include high-FP patterns. Useaction: scrubto redact matched content rather thanaction: block, which denies entire requests.pci_panis not a safe block set, because itsrouting_numberpattern matches many 9-digit numbers; to block card and bank-account data, tickcc,cvvandibanindividually.credentialsis strict and suitable foraction: block.
Custom patterns
custom_patterns accepts raw pattern strings written in Lua pattern syntax — for example %d for a digit, %a for a letter, and the +/*/- quantifiers. Lua patterns are not POSIX ERE or PCRE: they have no {N} counted repetition, so a fixed-length run of characters is written out explicitly (for example %d%d%d%d for four digits). Custom patterns are evaluated alongside any named patterns in the same guardrail instance.
Only a pattern that cannot run at all is refused when it is saved (400, nothing stored, the reason names the pattern and its position), on POST/PATCH /gateways and on the guardrail-config import and dry-run:
- a Lua syntax error — an unclosed
[set or(capture, a)without(, a trailing%,%bwithout two characters,%fwithout a[set], a back-reference such as%1to a capture that is not complete at that point (captures are numbered by their(); - more than 32 captures, or a pattern too deep for the matcher — each quantified item (
x?,x*,x+,x-) counts 1, each capture 2, each()position capture 1, and the matcher refuses a total of 200 or more at runtime; - a NUL byte in a pattern with special characters — the matcher ignores everything after it (match a NUL with
%z).
A pattern with none of the special characters ^ $ * + ? . ( [ % - is matched as plain text, so it is always accepted — Ltd) finds Ltd). There is no separate length limit. An exported guardrail config leaves out a stored pattern that cannot run (it never matched), so the file imports onto any gateway.
A pattern that runs is accepted, even when it can never match what you meant. Regular-expression habits are valid Lua patterns with a different meaning: \d{4} matches the literal text \d{4}, | is a literal bar, {3} literal braces, and a - after an item is a quantifier (lazy repeat of that item), so CUST-%d+ matches CUS123 but not CUST-123 — a literal hyphen is %-. Lua has no {N} counted repeat (write the item out, for example %d%d%d%d) and no | alternation (use one custom pattern per alternative). Check a pattern with Test against sample text in the Guardrail Builder (see below) before you rely on it.
A pattern of plain text such as 12345 is valid — it matches that text. Anchors (^ at the start, $ at the end) are accepted but anchor to the start / end of the whole scanned text — on the request phase that is the JSON request body, so an anchored pattern does not match a value inside a message. An anchored pattern is matched against the body as written, never per decoded level (the per-JSON-level read, which finds a value hidden behind a \uXXXX escape, skips it). A request scrub ignores anchored patterns; block and flag on the request match them as written; the response matches them as written for every action. On tool results anchored patterns are not applied. A pattern already stored on the same detector before this check is kept as it is; a pattern you add, change or copy to another detector is checked. Empty or non-text entries are ignored at runtime and are reported by the detector list as not covering anything.
Example configurations
Block requests containing card and bank-account data
curl -X PATCH "https://<your-gateway-host>/admin/v1/gateways/{id}" \
-H "Cookie: aig_admin=<SESSION>" \
-H "Content-Type: application/json" \
-d '{
"config": {
"guardrails": [
{
"type": "regex",
"name": "block-card-data",
"action": "block",
"target": "request",
"patterns": ["cc", "cvv", "iban"]
}
]
}
}'
Scrub credentials from requests and responses
Detects API keys and JWTs in both the outbound request and the inbound model response, replacing any matches with a custom placeholder.
{
"type": "regex",
"name": "scrub-credentials",
"action": "scrub",
"target": "both",
"patterns": ["credentials"],
"scrub_placeholder": "[REDACTED-CREDENTIAL]"
}
Scrub HIPAA-structured identifiers from requests
{
"type": "regex",
"name": "hipaa-scrub",
"action": "scrub",
"target": "request",
"patterns": ["hipaa_structured"]
}
Flag a custom internal ID format
Uses custom_patterns to match formats not covered by the named pattern library. This example flags any occurrence of an internal customer ID (CUST- followed by six digits — the hyphen is written %- because a bare - is a Lua quantifier), recording the match in the log without blocking or modifying the request.
{
"type": "regex",
"name": "internal-ids",
"action": "flag",
"target": "request",
"custom_patterns": ["CUST%-%d%d%d%d%d%d"]
}
💡 Note:
custom_patternsandpatternscan be combined in a single guardrail. Both lists are evaluated, and the configuredactionapplies if any pattern from either list matches.
Combine named patterns and custom patterns
{
"type": "regex",
"name": "combined-scrub",
"action": "scrub",
"target": "request",
"patterns": ["pii_basic"],
"custom_patterns": ["ACCT%-%d%d%d%d%d%d%d%d%d%d"],
"scrub_placeholder": "[PII]"
}
Configuring the regex guardrail
Regex guardrail card — expanded view
Proceed as follows to configure the regex guardrail in the Guardrail Builder:
- Open the gateway page (Organisation › AI setup › Gateways) and its Guardrails & residency tab with the Guardrails card.
- Click on the Regex / Pattern button.
- A collapsed regex guardrail card appears at the bottom of the list.
- Click on the card to expand it.
- Enter a name in the Name text field.
- Select the action from the Action drop-down list:
block,scrub, orflag. - Select the target from the Target drop-down list:
request,response, orboth. - Select one or more named pattern sets from the Pattern sets checkbox list (for example
credentials). - Select individual named patterns from the Individual patterns checkbox list (for example email, phone, or ssn). The Pattern sets and Individual patterns lists are tick-boxes — they do not accept raw expressions.
- To match an expression that is not in the named library, type a Lua pattern into the Custom patterns (Lua regex) field and click on the Add button (pressing Enter also adds it). Each added pattern appears as a removable chip; repeat for every custom pattern.
- On a saved gateway, the card of a detector whose target is
requestorbothalso shows Test against sample text (to users with theGATEWAYS_MANAGEpermission): paste a text and click on Test (or press Enter). The gateway runs the ticked and custom patterns as they are in the card — unsaved changes included — with the same matcher it uses for requests, on a request carrying that text, and shows Match (the detector would fire) or No match. The request is scanned as its JSON body, so a pattern that matches JSON punctuation or keys (for example%poruser) shows Match for any text — and would fire on every request. Nothing is saved. A pattern that cannot run — including one stored before this check — shows the reason instead of a verdict. The field is not available while creating a gateway; save it first.
- On a saved gateway, the card of a detector whose target is
- When the action is
scrub, the card shows a warning that the replacement is irreversible — nothing puts the original value back, in the answer or in the stored conversation — and points at the PII Protector, which masks reversibly. - If the action is
scruband you require a custom placeholder, enter the replacement text in the Scrub placeholder text field. - Click on the Save Guardrails button.
-> The regex guardrail is saved and appears in the execution plan.
JSON number fields
The scan reads the request body exactly as the provider will receive it, including numeric fields (a card number sent as a JSON number, a timestamp, an ID, a seed):
- Block mode sees the digits of a numeric field. Every number the gateway accepts is exact, and the scan sees its
exact digits; a whole number whose magnitude is below 2^63 is written as plain digits, while an accepted number of magnitude 2^63 or more keeps exponent
form (for example
1e+19) and its digits are not matched. A number the gateway cannot hold exactly (an integer literal a double cannot hold exactly such as9007199254740993, or beyond 2^63, or more than 17 significant digits) is refused before the guardrails run (number_not_exact); see Numbers in the request body are forwarded exactly. This is a behaviour change for requests that carry sensitive values in numeric fields. The same scope as scrub applies: a pattern also blocks on timestamps and IDs that aphone,npi,ssnorrouting_numberpattern matches, and on the fraction digits of a float such as0.30000000000000004. - Scrub (mask) mode never rewrites a number. When a pattern matches, wholly or partly, inside a JSON number
(a card number, but also any 9- or 10-digit timestamp or ID that a pattern such as
phone,npi,ssnorrouting_numbermatches), the request is blocked with the reasonpii_in_numberinstead of being masked. Matches inside text (strings) are masked as usual. Any digit run inside a JSON number counts, including the fraction digits of an ordinary float:{"temperature":0.30000000000000004}carries a 16-digit run, so aphonescrub blocks it withpii_in_number, while{"temperature":0.7}passes. Remedies: send the value as a string, round it client-side, or use a narrower custom pattern.
The refused value is not kept in the log. A request this scrub refuses (pii_in_number, scrub_uncommittable) is stored in the request log with its prompt masked by this detector's own rule (or, where that cannot be verified, the whole message withheld), never as sent; see the prompt column. A block or flag action keeps the prompt as sent.
Pipeline position
The regex guardrail is Tier 1 — it runs in-process with no external calls. All Tier 1 guardrails run before any Tier 2 guardrail. When multiple regex guardrails are configured, they run in the order they appear in the guardrails array.
A block verdict from this guardrail stops the pipeline immediately. No subsequent guardrails run.
The block verdict reports the first pattern that matched. In the web app the block notice names the kind of data for the built-in patterns cc, cvv and card_expiry (credit card), iban and routing_number (bank account), and ssn, national_id and passport_number (ID number). A request that contains several kinds of data is reported under the first pattern that matched. Other patterns and custom patterns keep the general notice.