Regex detection for custom identifiers in NeMo Guardrails: when teams need it
Teams need regex detection for custom identifiers when their assistant handles values that general PII detectors do not recognize, such as account numbers, medical record numbers (MRNs) or internal ticket IDs. Presidio, GLiNER-PII and Private AI are built to find common personal data categories like names, phone numbers and email addresses, so an internal format like ACC- followed by ten digits can pass straight through them. A regex rail closes that gap by matching a pattern you define for your own identifier. The NeMo Guardrails documentation describes the rail types that can host these checks, and the library is open source under the Apache 2.0 license, so the pattern logic is yours to inspect and change.
Regex rails can be placed on three points in the flow. An input rail checks the user's prompt before the model sees it, an output rail checks the model's response before the user does, and a retrieval rail checks chunks pulled from your knowledge base before they enter the prompt. Start by listing where each identifier can appear. A support assistant may receive MRNs in user prompts, echo them in responses, and retrieve them from clinical notes, and each of those places needs its own decision about whether to block the request or mask the value. Confirm the exact rail configuration keys and action options for your installed version in the NeMo Guardrails documentation before you write the config.
Regex is best for identifiers with a fixed, predictable format, and it sits alongside the model-based detectors rather than replacing them. Keep Presidio, GLiNER-PII or Private AI for personal data that varies in form, and use regex for the structured internal values you control. Before you rely on a pattern, confirm with the owners of each identifier how it is formatted, whether check digits exist, and whether the same digit sequence appears in unrelated fields, since those are the main sources of false positives.
Configuration options and when each fits
This table compares the main configuration choices for regex rails on custom identifiers: blocking or masking, placement on input, output or retrieval, and how patterns are organized. Read each row for what the user experiences, what the model still receives and where over-matching is most likely. The main takeaway is that masking and broad shared patterns carry the highest over-matching risk, so test each pattern against representative traffic before enabling it.
| Option | User experience | What the model still sees | Over-matching risk |
|---|---|---|---|
| Block the request or response | User receives a refusal and must rephrase without the identifier | Nothing, because the call never reaches the model | Legitimate requests containing look-alike numbers are refused outright |
| Mask the match and continue | User gets an answer, with the identifier replaced by a placeholder | A placeholder token in place of the identifier | Masked digits can change meaning, for example a part number or date that resembles an account number |
| Input placement | Matches are caught before the model call, so the user sees the block or mask immediately | Only the sanitized prompt, provided the rail runs before the call | Identifiers the user must discuss, such as a ticket ID in a question, get blocked or masked |
| Output placement | Matches are caught after generation, so the user may see a partly masked reply | The raw identifier, because the model already produced or received it | Identifiers the user supplied earlier in the conversation get masked in the reply |
| Retrieval placement | Users see answers built from masked knowledge, with no direct sign of the masking | Masked chunks only, so the prompt holds no raw identifiers from the knowledge base | Internal document IDs used for citation or lookup are masked, which can break traceability |
| One pattern per identifier | No visible difference to users | Same as the chosen outcome, applied per identifier type | Lower collision risk, since each pattern is tested alone, but more patterns to maintain as identifiers change |
| Shared pattern library | No visible difference to users | Same as the chosen outcome, applied across all matched types | Higher collision risk, since generic digit runs can match several identifier families at once |
| Regex alone | Predictable behavior that is easy to explain to reviewers | Anything the patterns miss, including free-text or misspelled identifiers | Low on fixed formats, but it cannot tell a real account number from a similar string in context |
| Regex ahead of a model-based detector | Exact formats are handled first, with the detector covering the remaining cases | Placeholders for regex matches, plus whatever the detector finds in the rest of the text | Regex false positives are treated as certain, and the detector may see placeholders it does not expect |
Set up regex rails for custom identifiers
This sequence takes a team from a compatible Python environment to a tested NeMo Guardrails configuration that catches internal identifiers on input, output and retrieved content, with evidence that each rail matches what it should and nothing else.
Confirm Python and package versions
The engineer responsible for the application confirms the runtime before installing anything. NeMo Guardrails 0.25.0 requires Python 3.11, 3.12 or 3.13, so the team pins the interpreter and installs the
nemoguardrailspackage from PyPI at a pinned version in a virtual environment. Confirm the install by running the package version check and recording the output in the change record. The step is done when the environment imports the library cleanly on the same interpreter your deployment image will use.Write config.yml and Python actions
The platform or security engineer creates the configuration folder with a config.yml file, declares the input, output and retrieval rails you plan to use, and adds a Python action only where a regex check needs logic beyond a pattern, such as checksum validation. Keep action code in the same folder so the configuration is versioned as one unit. The step is done when the server or Python API loads the folder without configuration errors and lists the rails it expects to run.
Define identifier formats with data owners
Work with the data owners for each internal identifier, such as account numbers, medical record numbers and ticket IDs, to agree the exact format: length, prefix, allowed characters, check digits and where the identifier appears. Ask for a set of sample values, including real-format examples that are safe to use in testing and known near-miss values that must not match. Record each format as a pattern with its owner and the systems that issue it. The step is done when every identifier has a written format and an owner who has reviewed the samples.
Add input and output regex rails
Add the regex patterns to the input rail and the output rail in the configuration, using one named rule per identifier so that a match reports which identifier type was found. Decide per identifier whether a match blocks the request or masks the value and lets the flow continue, and encode that choice in the rail outcome. The step is done when a test request containing a sample identifier triggers the expected rail and the logged outcome names the identifier type without repeating the full value.
Add retrieval rails for RAG content
If the application retrieves documents or knowledge chunks, attach the same identifier rules to the retrieval rail so that matching content is handled before it enters the prompt. Confirm that your version of NeMo Guardrails supports retrieval rails for the retrieval path you use, since support depends on how the knowledge is fetched. The step is done when a chunk containing a sample identifier is masked or blocked before generation, and a chunk without one passes unchanged.
Test positive and negative strings per pattern
The QA or security engineer builds a test set for each pattern with positive strings that must match, negative strings that must not match, and boundary cases such as a number of the right length with the wrong check digit or a ticket ID embedded in a longer code. Run the set through the rails directly, not only through the chat interface, and record each result. The step is done when every positive case triggers its rule and every negative case passes, with the results saved as test evidence.
Check for over-matching before release
Run a larger sample of ordinary traffic, such as product codes, order numbers, dates, phone-like numbers and log fragments, through the same rails to measure which benign strings the patterns catch. Tighten anchors, context words or validation logic for each false positive, then rerun the full test set so earlier fixes do not break earlier cases. The step is done when the over-matching sample produces an acceptable and documented list of exceptions agreed with the data owners, and the rerun passes in full.
Record configuration and test evidence
The platform team stores the configuration folder, action code, pattern list with owners, test sets and results in version control, and tags the release with the NeMo Guardrails version used. Keep the logs of rail outcomes in a form that shows identifier types without exposing values. The step is done when a reviewer can rebuild the configuration from the repository, rerun the tests and trace each pattern to an owner and a test result.
Testing patterns for over-matching
Start by testing each regex in isolation, before it is wired into any rail. Build two labeled corpora for every custom identifier: a positive set containing well-formed examples of the identifier in the formats your systems actually produce, and a negative set containing strings that look similar but are not the identifier. The negative set is where over-matching is found, so it should be the larger and more deliberate of the two. Include dates such as 2024-03-18 and 18/03/2024, order numbers, phone-like digit runs, product codes and version strings, because these share the shape of many account or record numbers.
- Positive corpus: Cover every format variant, separators, leading zeros and the boundary cases where the identifier sits next to punctuation.
- Negative corpus: Collect near misses from order systems, product catalogs and date fields, and mark each one with the reason it should not match.
- Anchoring tests: Confirm that the pattern respects word boundaries, so
ACC-1042does not match inside a longer token. - Measured results: Record false positives and false negatives per corpus, so a change to one pattern can be compared against its previous run.
- Ship criteria: Decide in advance the false positive level that blocks release, and treat a pattern that matches any sample from a negative category you defined as too broad until it is narrowed.
Check that each test run is repeatable and stored with the pattern, so reviewers can see why a pattern was accepted.
Unit corpora are written by people and tend to miss the strings real users type. Replay is the step that tests a pattern against realistic volume. Take recent prompts, retrieved chunks and model responses, remove personal and confidential content through your approved de-identification process, and run them through the rails in a non-production environment with the pattern set in detect-only mode. Replaced values should keep their structure, so the regex still sees a string of the same shape. The goal is to count how often the rail fires and on what, not to block anything yet.
- Match review: Sample every distinct matching shape and label it as a true identifier, a date, an order number, a phone-like string or a product code.
- Rate tracking: Compare the number of matches per thousand requests across each category, and look for sudden growth after a new product or form launches.
- Source breakdown: Separate input, output and retrieval matches, since retrieved documents often contain catalog codes that users never type.
- Access to replay data: Confirm who can view the de-identified set, and where it is stored, before copying any traffic out of production.
Confirm your de-identification method with your privacy and compliance owners before replay begins, because a poorly masked sample can itself create a data exposure.
Every change to a pattern, a rail order, an action or a model can alter what matches. Regression runs make those effects visible before deployment. Keep the labeled corpora, the replay sample and the expected results under version control with the Colang and config.yml files, and run the full set in continuous integration whenever any of them changes. A change that looks local, such as widening a digit count, can affect input rails, output rails and retrieval rails at once, so the run should cover all of them.
- Baseline comparison: Store the previous match counts per corpus, and fail the run when a category's false positives rise beyond the threshold your team agreed.
- Rail coverage: Test each rail path separately, since an input rail may pass a string that a retrieval rail later blocks.
- Version pinning: Record the NeMo Guardrails version used for each run, because library upgrades can change how rails are loaded and executed. Check the upgrade notes for the version you are moving to.
- Rollback test: Confirm that a previous pattern set can be restored quickly if a new one causes blocking in production.
Ask your team to define who approves a threshold change, since that decision determines how much over-matching the business accepts.
Security and operational considerations for regex rails
Regex rails are simple to write and easy to get wrong in production. The cards below cover the places where a custom pattern can leak data, slow down requests, drift from its intended scope or fail without anyone noticing, and what to check in your deployment before relying on them.
Identifiers leaking into logs
A regex rail that matches an account number is only safe if the matched text stays out of logs, debug output and traces. Check what the rail logs when it blocks or masks, including the matched substring, the rail name and the surrounding prompt. Confirm that verbose logging is off in production and that the log level used by your server does not echo rejected input. Treat any log line that contains a match as sensitive data with the same retention and access rules as the identifier itself.
Catastrophic backtracking on large inputs
Some regular expressions take exponential time on specific inputs, a failure known as ReDoS. A pattern with nested quantifiers or overlapping alternatives can stall a worker when a user pastes a long string or a retrieved chunk is unusually large. Test every pattern against long, near-matching inputs and measure the time per request. Set input length limits upstream of the rails so a single oversized message cannot hold a worker for an unbounded period.
Pattern files as sensitive configuration
Patterns reveal how your identifiers are formatted, such as the prefix and length of internal ticket IDs or medical record numbers. Store the Colang and configuration files that hold them in version control with restricted write access, and keep them out of public repositories and container images that others can pull. Confirm which service accounts can read the configuration folder on the guardrails server and whether the pattern files are copied into logs or support bundles.
Change control for pattern updates
A small edit to a pattern can silently widen or narrow what gets blocked. Require every change to go through review with a test set that includes known positives, known negatives and recent false positives. Record who approved each change and which version of the configuration is running in each environment. Confirm that a rollback path exists and that the production configuration matches the reviewed revision.
Masked values and tracing settings
When a rail masks a value, the original identifier may still be present in traces, cached prompts or request payloads recorded by an upstream gateway. Verify whether the tracing and content capture settings record the input before or after masking, and whether that choice matches your data handling policy. Ask your observability team to confirm the retention period for those traces, and test a masked request end to end to see what is stored.
NeMo Guardrails docsOver-matching and ownership of rules
Custom identifier patterns often match order numbers, dates or internal reference codes that are not personal data, which blocks legitimate traffic. Assign an owner for each pattern who reviews false positives on a schedule and can justify its scope to the security team. Confirm that the owner can see rail decisions in aggregate without seeing the raw identifiers, so tuning does not spread the data it is meant to protect.
Questions buyers ask before adding custom identifier detection
How much effort does writing custom regex patterns for identifiers take?
Effort depends mostly on how many identifier formats you have and how well each one is documented. A single format with a published check digit and clear samples is a short task. Each additional format adds pattern design, sample collection, negative examples and tests, so the work grows with the format count rather than with the size of the code change. No supplied figure sets a duration, so ask any provider to break the quote into formats, test corpus work and rollout steps. Regex rails in NeMo Guardrails are configured through the config.yml file and optional Python actions, so the configuration itself is rarely the largest item.
What drives the cost of custom identifier detection up or down?
The main drivers are the number of identifier formats, whether sample data exists, the retrieval scope, and the size of the test corpus. Formats with no examples need data owners to produce or approve synthetic samples, which adds time. Retrieval rails that scan knowledge bases across many sources widen the test surface compared with input rails alone. A larger corpus of realistic benign text, used to measure over-matching, costs more to assemble but reduces surprises after launch. Ask a quote to state each driver as a line item so you can see which choices move the price.
What do we need from our data owners before the work starts?
Data owners need to confirm the exact format of each identifier, including length, prefix, allowed characters and any check digit. They should provide anonymized or synthetic samples that match production shape, and say which values must never be stored in logs or traces. They also need to name which systems emit identifiers, such as core banking, the EHR or the ticketing tool, and which teams may approve false positives. Without these inputs, patterns are guesses. Ask the provider which of these items it expects you to supply and which it will generate.
Can our internal team build and maintain these patterns without outside help?
Yes, a team with Python and regex experience and access to the NeMo Guardrails configuration can build simple patterns in-house. The harder parts are the negative test set, the review of over-matching, and keeping patterns aligned when identifier formats change. Internal teams often underestimate how much review time false positives take from the people who own the data. Decide who will own each pattern after launch, because the rail configuration needs a change process just like application code. An outside partner is useful when formats are numerous, the deadline is fixed, or you need evidence for a compliance review.
How long does a first pass of custom identifier detection take?
A first pass scales with scope: the number of formats, the rails in use (input, output or retrieval), and how many test samples are needed. No researched figure gives a duration for this work, so treat any timeline as provisional until the scope is written down. A reasonable first pass covers a small set of formats on input and output, with a test corpus and a measured false-positive review. Broader retrieval coverage and multiple data owners extend it. Ask for milestones tied to the written scope and a retest before go-live.
How do we know a regex rail is over-matching?
Test each pattern against a corpus of benign text that resembles your real traffic, including order numbers, dates, phone numbers and product codes that share digit patterns with your identifiers. Count every match, then review a sample by hand with the data owner. Patterns that match ordinary strings need tighter anchors, context words, length limits or check-digit validation. Re-run the same corpus after every change so a fix for one format does not break another. Record the results so you can show the review process to an auditor.
Does DeployOpen handle custom identifier detection, and what does it deliver?
DeployOpen implements self-hosted open-source platforms in your own infrastructure and runs security testing, including AI system testing. For guardrail work, the scope can cover pattern design, configuration of input, output and retrieval rails, a test corpus for over-matching, and a findings report with fixes and a retest. Scope, deliverables and timelines are agreed in writing before work starts, and DeployOpen does not publish a price list, so a quote follows the written scope. DeployOpen does not issue audit reports or certifications; independent auditors assess those.
Where regex checks sit in a request flow
The flow starts with a user message entering the application, where an input regex rail checks it before any model call. Clean messages pass to the model endpoint, which sits across the trust boundary outside your application. The output rail then checks the response, and a retrieval rail checks RAG chunks before they join the prompt. The logging boundary marks which copies of matched text may be written to logs and traces, so check that masked values are what cross it.
Regex rails at input, retrieval and output, with the trust and logging boundaries marked.
How DeployOpen scopes and delivers custom identifier rails
DeployOpen approaches regex detection for custom identifiers as a scoped engineering task: first the identifier formats and where they appear, then rails built on NeMo Guardrails and tested for over-matching before handover. Engagements are fixed-scope, with the scope, deliverables and timeline agreed in writing before work starts.
How we scope
- Inventory the identifiers your teams need caught, such as account numbers, medical record numbers and internal ticket IDs.
- Collect sample formats and known look-alike values so the written scope defines what must match and what must not.
- Agree in writing which rail points apply: input, output, retrieval or a combination, and the action on match.
How we build
- Write regex patterns in configuration files alongside the NeMo Guardrails config.yml and Colang files for your environment.
- Wire each pattern to the chosen rail and action, keeping block and mask behavior explicit for each identifier type.
- Test every pattern against positive samples, negative samples and near-miss values before it reaches a shared environment.
How we hand over
- Deliver the pattern library, rail configuration, test cases and an over-matching report with the known false positives listed.
- Document how to add or change a pattern, who approves changes and how to rerun the test suite after an edit.
- Walk your engineering and security teams through the configuration and the evidence produced by the tests.
How we support
- Retest patterns after NeMo Guardrails upgrades or when your identifier formats change.
- Ongoing support, upgrades and continuous testing are available as retainers, scoped in writing.
- Confirm with your team which owner reviews new false positives and how logs and traces handle matched values.

