DeepSeek can help turn a text rule into a regular expression, explain unfamiliar syntax, and suggest cases you might otherwise overlook. The useful deliverable is a candidate you can inspect and test. Before accepting it, you need a written contract, expected results that remain under your control, and an execution environment that matches your application.
This tutorial develops that workflow around a fictional stock code. You will define the allowed characters, ask for a bounded pattern, check exact captures, challenge near misses, and decide when a plain string operation or parser would be easier to maintain. The examples use Python strings and the standard library regular expression engine. You can follow the reasoning in another language, but you must recheck its syntax and behavior.
Scope: the prompts and examples below are author-created teaching material. They are not transcripts of a DeepSeek session. No claim is made about a model’s measured accuracy, and you do not need a paid API call to run the accompanying local checks.
Start with a contract that someone can disagree with
A request such as “write a regex for product IDs” leaves most of the important decisions unstated. It does not say whether lowercase letters are acceptable, whether an identifier can appear inside a sentence, or whether a trailing newline should be discarded. An assistant can fill those gaps plausibly while producing behavior that your application never intended.
For this exercise, imagine that a warehouse intake field accepts one stock code. Its owner has proposed the following rules. In a real project, the responsible reviewer would approve these decisions before the expression becomes a release candidate.
- The prefix contains exactly two uppercase ASCII letters, from A through Z
- A literal ASCII hyphen separates the prefix from exactly four ASCII digits, from zero through nine
- An optional suffix consists of one more literal hyphen followed by exactly one of S, M, or L
- The complete input must contain exactly seven or nine characters
- No whitespace, additional characters, trimming, case conversion, or Unicode normalization is allowed
- A successful parse preserves the prefix and four-digit number as strings and represents an absent size with a null-like value
The fictional code AB-0042-M therefore has prefix AB, number 0042, and size M. The code AB-0042 is equally valid, with no size. The leading zeros matter because this field is an identifier. Converting the number portion to an integer would lose information that a downstream label printer might need.
Give the contract a location and an owner. A small project might keep it immediately above a fixture list in a test file. A larger application might put it in a versioned interface specification. Either way, a pattern change should point back to the relevant rule. “The assistant suggested it” cannot explain a decision to accept a previously invalid customer submission.
Also separate format validity from business validity. A code can have the right shape and still refer to no stocked item. Inventory existence, user permission, and availability require application checks. Keeping those concerns explicit prevents a successful regex match from acquiring more authority than it deserves.

Ask DeepSeek for a reviewable candidate
Supply the engine, operation, input type, normalization policy, and required output together. Ask the assistant to identify unresolved questions before inventing new rules. A candidate accompanied by assumptions is easier to review than an elaborate expression whose choices are hidden inside lookarounds.
The following prompt is an author-created template. Replace the runtime line with your deployed version, and add your existing reviewer-approved examples when working on a real system. Avoid uploading production identifiers or logs when synthetic cases describe the same problem.
Propose a regular expression for this written contract.
Runtime: Python 3 standard-library re; input is str.
Operation: full-input validation, followed by named captures.
Flags: no optional matching flags.
Input: exactly two uppercase ASCII letters, an ASCII hyphen,
exactly four ASCII digits, and optionally an ASCII hyphen plus
one size letter from S, M, L. Total length is 7 or 9 characters.
Do not trim, normalize, or change case.
Captures: prefix, number, size. Keep number as a string.
An absent size must be None in the Python result.
Return:
1. One candidate pattern and the exact matching API.
2. A short explanation tied to each contract rule.
3. Assumptions or unanswered questions.
4. Suggested additional cases, clearly separated from the fixed tests.
Do not modify expected results in the supplied fixtures.
Do not claim you executed code unless an execution result is available.
Structured output can make repeated reviews easier. You might request separate fields for the pattern, flags, operation, assumptions, and proposed cases. This keeps a newly suggested exception from disappearing into explanatory prose. If you are building a repeatable assistant workflow, the related guide to structured outputs with DeepSeek develops that handoff in more detail.
Keep a record of the candidate you actually tested. Copying a slightly different pattern from a later response can invalidate an otherwise useful test report. Store the expression as source text, record the flags and wrapper function, and review changes through the same mechanism you use for ordinary application code.
Read the pattern against the contract
Here is the proposed expression used throughout this tutorial. It is deliberately small enough to inspect one component at a time.
(?P<prefix>[A-Z]{2})-(?P<number>[0-9]{4})(?:-(?P<size>[SML]))?
The prefix component allocates two positions to uppercase ASCII letters. The first separator is fixed. The number component allocates four positions to the explicit digit range. The final optional unit contains both its separator and its size letter, so accepting the suffix means accepting those two characters together.
That grouping is worth checking carefully. If a revision makes only the letter optional while leaving its hyphen mandatory, the no-size form changes. If it makes the separator optional independently, a missing separator may slip through. Read the optional unit aloud as “either no suffix, or a hyphen followed by one permitted size.”
The three names describe the return contract. The outer suffix grouping exists only to apply optionality and adds no extra output field. There is no business need here for a wildcard, an arbitrary-length repeat, a backreference, or a lookbehind. If a candidate introduces one, ask which written requirement makes it necessary.
For this specific expression, the length rule follows directly from the components: two letters, one separator, and four digits make seven characters; the optional suffix adds two. The wrapper repeats that bound before matching so that a reader can see it at the entry point. Redundant clarity can be helpful when it expresses an important interface restriction.
Choose validation, extraction, or replacement explicitly
Validation consumes the complete field
Python’s regular expression reference distinguishes searching anywhere, matching from the beginning, and matching the whole string. This validator uses fullmatch on the original input. The application asks whether the entire submitted field conforms to the stock-code contract.
Consequently, a sentence containing AB-0042 is invalid as a stock-code field. So is AB-0042 followed by an extra hyphen, a space, or a newline. Finding a legitimate-looking fragment inside any of those values would answer a different question. A useful review includes the calling code because a correct expression paired with the wrong operation can still accept the wrong input.
Avoid mechanically replacing the full-match operation with start and end anchors. Python’s dollar anchor can match before a final newline, and multiline mode affects anchor behavior. The chosen operation makes the complete-input requirement visible without relying on a reader to reconstruct those details.
Extraction needs its own boundary rules
Suppose a later feature needs to locate stock codes in warehouse notes. Decide whether a code adjacent to a letter, digit, underscore, or hyphen counts as a separate token. Decide whether punctuation belongs to the result and whether malformed longer identifiers can contain eligible shorter fragments. These are new acceptance decisions.
For example, a note containing AB-0042-XL should not automatically yield AB-0042 merely because the short form is valid by itself. Whether that partial extraction is useful depends on the note-processing contract. Write the expected spans as well as the expected text. Two extractors can return the same characters from different places in a document.
For a known literal needle, the companion examples use an escaped search rather than interpreting the needle as a pattern. A needle containing parentheses or a plus sign should still mean those literal characters. This narrow helper demonstrates extraction mechanics without pretending to solve stock-code tokenization in arbitrary prose.
Replacement needs a change contract
Replacement adds another set of questions: which occurrences change, how many may change, and what happens when there is no match? Establish those answers before asking for implementation. A “clean up codes” instruction is too broad for a process that might edit thousands of records.
The companion literal replacement helper limits input size and replacement count, and uses a callable so supplied replacement text remains literal. For a batch job, also compare the complete before-and-after result and record the number of changes. Run a preview on a copy before approving a write to original data.
Search patterns and replacement templates have separate interpretation rules. Escaping a search needle does not establish that a replacement template is literal. A test containing backslashes in the replacement is a small, practical way to catch an assumption that ordinary words would conceal.
Keep the validator wrapper small and explicit
The main helper below returns the three named fields when the input is valid and returns None for an invalid string. It raises TypeError for non-string input. These choices belong to the wrapper’s public contract and should be tested alongside the expression.
The length check runs before matching. There is no call that strips whitespace, uppercases characters, or replaces separators. Reviewers can therefore inspect the entire transformation path in one place. A convenience boolean helper can call the parser when the caller needs only acceptance, while callers needing fields retain the richer result.
import re
STOCK_CODE = re.compile(
r"(?P<prefix>[A-Z]{2})-(?P<number>[0-9]{4})(?:-(?P<size>[SML]))?"
)
def parse_stock_code(value: str) -> dict[str, str | None] | None:
"""Return exact captures, or None; never trim, normalize or change case."""
if not isinstance(value, str):
raise TypeError("stock code must be a string")
if len(value) not in (7, 9):
return None
match = STOCK_CODE.fullmatch(value)
return match.groupdict() if match else None
def is_stock_code(value: str) -> bool:
return parse_stock_code(value) is not None
For AB-0042-M, the expected result contains prefix “AB”, number “0042”, and size “M”. For AB-0042, the same prefix and number remain, and size is None. Python’s named-group dictionary uses None by default when an optional group does not participate.
Assert the whole result, including key names and value types. A boolean assertion cannot catch a renamed field, discarded leading zeros, or an empty string substituted for an absent size. Such mistakes can break a caller even when the acceptance decision remains correct.
Do not quietly coerce incoming numbers, bytes, or arbitrary objects into strings. If an upstream adapter must decode bytes, give that adapter an encoding and error policy, then test the boundary separately. A validator should receive the kind of input its contract describes.
Build examples that can reject a plausible answer
Start the fixture set before showing a candidate to the assistant. Include ordinary valid values, each optional branch, and cases close enough to valid input that a single misplaced quantifier would accept them. Writing expected outcomes first reduces the temptation to explain away a failing case after seeing the generated expression.
A useful negative case should have a reason. One lowercase prefix character challenges the case rule. Three digits challenge the exact width. An unsupported size challenges membership in the permitted set. A trailing hyphen challenges whether the optional suffix was grouped correctly. Keep these reasons close to the fixtures so later reviewers can understand why the cases exist.
Test values around both permitted lengths, including values with the correct length but wrong content. A seven-character string is only a candidate for validation. Length alone says nothing about whether its third character is a hyphen or whether its first two characters belong to the required alphabet.
Include leading and trailing spaces, a tab, a line feed, and a carriage-return/line-feed ending. Represent invisible characters with escaped forms in test labels. A failing report that visibly prints only AB-0042 can otherwise look identical to a valid fixture, slowing diagnosis and inviting the wrong repair.
Positive tests deserve similar care. Use leading zeros, different prefix letters, and each permitted size. Check the no-size result independently. If all valid fixtures have size M, an expression accidentally limited to M could survive the positive set.
The companion file includes a deliberately broad counterexample with variable prefix and digit widths, a general digit shorthand, and a one- or two-letter size. It is an author-created teaching mistake, not an observed DeepSeek response. Its flexibility looks convenient until you compare it with the fixed contract.
A-1 challenges both mandatory widths. ABC-12345 challenges both upper bounds. AB-1234-XL challenges the size alphabet and length. A code containing Arabic-Indic digits challenges the ASCII requirement. Each example explains a specific rejection, making the review more informative than a collection of unrelated invalid strings.
Keep even deliberately incorrect teaching patterns bounded. The companion counterexample runs only against short, fixed values; it is not a ReDoS demonstration or a license to execute arbitrary model-generated expressions.
The accompanying checks also compare the regex decision with a separately written, non-regex interpretation of this small contract and exercise a finite set of single-character mutations. That gives two implementations something concrete to disagree about. It still requires review because both could share a mistaken interpretation of the requirement.
What actually ran: the complete standard-library script below passed 15 unittest methods on CPython 3.12.14. It checked five positive fixture rows with exact captures, 38 negative fixture rows, and 2,911 finite single-character replacement comparisons across 2,875 distinct inputs, including the five original seed strings, with zero disagreements against the separate non-regex oracle. A warning-as-error syntax check also passed. The replacement comparisons are coverage within one test method, not 2,911 independent test methods.
The script includes an intentionally incorrect, bounded candidate. It accepts eight of the 38 negative fixtures; the tests pass by detecting those mistakes. That candidate is an authored counterexample, not a captured DeepSeek response. Only the explicit reviewed patterns in this script ran. No API calls, arbitrary generated patterns, timing benchmarks, or production inputs were used.
Save the expanded code as regex_workflow.py and run python regex_workflow.py -v. The main helper above is repeated inside the complete script so the script can run on its own. Its type annotations require Python 3.10 or later; execution here was checked only on the recorded 3.12.14 runtime. Review the fictional fixture expectations for your own project before adopting them.
Show the complete offline Python test script
"""Contract-first regex examples; standard library only, Python 3.10+ syntax.
Run: python regex_workflow.py -v
Fixtures belong to the contract reviewer: do not change their expected answers
to make a candidate pass. These tutorial fixtures still need human sign-off.
No DeepSeek/model call is made, and no unreviewed model output is executed.
"""
import re
import unittest
STOCK_CODE = re.compile(
r"(?P<prefix>[A-Z]{2})-(?P<number>[0-9]{4})(?:-(?P<size>[SML]))?"
)
def parse_stock_code(value: str) -> dict[str, str | None] | None:
"""Return exact captures, or None; never trim, normalize or change case."""
if not isinstance(value, str):
raise TypeError("stock code must be a string")
if len(value) not in (7, 9):
return None
match = STOCK_CODE.fullmatch(value)
return match.groupdict() if match else None
def is_stock_code(value: str) -> bool:
return parse_stock_code(value) is not None
# Immutable fixture rows: input, then exact (prefix, number, size) expectation.
# The number stays text, including leading zeros; missing size is None.
POSITIVE = (
("AB-0000", ("AB", "0000", None)),
("ZZ-9999", ("ZZ", "9999", None)),
("AA-0001-S", ("AA", "0001", "S")),
("BC-2048-M", ("BC", "2048", "M")),
("XY-8765-L", ("XY", "8765", "L")),
)
NEGATIVE = (
"", "A-1234", "ABC-1234", "ab-1234", "Ab-1234", "1B-1234",
"_B-1234", "AB1234", "AB_1234", "AB-123", "AB-12345",
"AB-12A4", "AB-1234-", "AB-1234S", "AB-1234-XL", "AB-1234-X",
"AB-1234-s", "AB-1234-S-M", " AB-1234", "AB-1234 ", "AB- 1234",
"AB-1234\n", "AB-1234-S\n", "\nAB-1234", "AB-12\n34",
"AB-1234\r\n", "AB-1234\t", "AB-1234\x00", "AB-1234\u00a0",
"AB-\u0661\u0662\u0663\u0664", # Arabic-Indic decimal digits.
"AB-\uff11\uff12\uff13\uff14", # Fullwidth decimal digits.
"\uff21\uff22-1234", "\u212aB-1234", "AB\u20111234",
"order AB-1234 ready", "xAB-1234", "AB-1234x", "AB-1234-S!",
)
def reference_accepts(value: str) -> bool:
"""Independent oracle for tests: implement the stated contract without regex."""
if len(value) not in (7, 9):
return False
if any(char not in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for char in value[:2]):
return False
if value[2] != "-" or any(char not in "0123456789" for char in value[3:7]):
return False
return len(value) == 7 or (value[7] == "-" and value[8] in "SML")
# Deliberately wrong, explicitly reviewed and run only against short fixed inputs.
# It is a teaching counterexample, not claimed to be an actual model response.
BROAD_CANDIDATE = re.compile(r"[A-Z]{1,3}-\d{1,5}(?:-[A-Z]{1,2})?")
BROAD_FALSE_POSITIVES = ("A-1", "ABC-12345", "AB-1234-XL", "AB-\u0661\u0662\u0663\u0664")
def literal_pattern(text: str, needle: str) -> re.Pattern[str]:
"""A bounded, literal substring example; no token-boundary semantics."""
if len(text) > 4096 or not 1 <= len(needle) <= 64:
raise ValueError("text must be <=4096 characters; needle must be 1..64")
return re.compile(re.escape(needle))
def find_literal_spans(text: str, needle: str) -> list[tuple[int, int]]:
return [match.span() for match in literal_pattern(text, needle).finditer(text)]
def replace_literal(text: str, needle: str, replacement: str, *, limit: int = 2) -> str:
if type(limit) is not int or not 1 <= limit <= 10 or len(replacement) > 128:
raise ValueError("limit must be an integer 1..10; replacement must be <=128")
pattern = literal_pattern(text, needle)
return pattern.sub(lambda _match: replacement, text, count=limit)
class StockCodeTests(unittest.TestCase):
def test_positive_fixtures_and_exact_groups(self):
for value, expected in POSITIVE:
with self.subTest(value=value):
self.assertTrue(is_stock_code(value))
self.assertEqual(parse_stock_code(value), dict(zip(("prefix", "number", "size"), expected)))
self.assertEqual(STOCK_CODE.fullmatch(value).groups(), expected)
def test_negative_fixtures(self):
for value in NEGATIVE:
with self.subTest(value=value):
self.assertFalse(is_stock_code(value))
self.assertIsNone(parse_stock_code(value))
self.assertIsNone(STOCK_CODE.fullmatch(value))
def test_non_string_input_is_an_error(self):
for value in (None, 1234, b"AB-1234"):
with self.subTest(value=value), self.assertRaises(TypeError):
parse_stock_code(value)
def test_reference_oracle_agrees_on_fixtures(self):
for value, _ in POSITIVE:
self.assertTrue(reference_accepts(value))
for value in NEGATIVE:
self.assertFalse(reference_accepts(value))
def test_single_character_mutations_against_oracle(self):
# Finite coverage, not an exhaustive proof; expectations do not use regex.
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_ \n\t\u0661\uff11\u212a\x00"
for base, _ in POSITIVE:
for index in range(len(base)):
for char in alphabet:
value = base[:index] + char + base[index + 1:]
with self.subTest(value=value):
self.assertEqual(is_stock_code(value), reference_accepts(value))
def test_search_is_not_validation(self):
value = "order AB-1234 ready"
self.assertEqual(STOCK_CODE.search(value).group(0), "AB-1234")
self.assertIsNone(STOCK_CODE.fullmatch(value))
def test_dollar_anchor_allows_final_newline(self):
value = "AB-1234\n"
self.assertIsNotNone(re.match(r"^[A-Z]{2}-[0-9]{4}$", value))
self.assertIsNone(STOCK_CODE.fullmatch(value))
def test_reviewed_broad_candidate_has_known_false_positives(self):
# These assertions PASS by detecting a wrong candidate's bad decisions.
for value in BROAD_FALSE_POSITIVES:
with self.subTest(value=value):
self.assertIsNotNone(BROAD_CANDIDATE.fullmatch(value))
self.assertFalse(is_stock_code(value))
class LiteralTests(unittest.TestCase):
def test_search_metacharacters_are_literal(self):
self.assertEqual(find_literal_spans("a.b aXb a.b", "a.b"), [(0, 3), (8, 11)])
self.assertEqual(find_literal_spans("[x] x [x]", "[x]"), [(0, 3), (6, 9)])
self.assertEqual(find_literal_spans("a+b aaab", "a+b"), [(0, 3)])
def test_replacement_is_literal_and_count_is_bounded(self):
replacement = r"C:\new\items\1"
self.assertEqual(
replace_literal("a.b aXb a.b a.b", "a.b", replacement),
replacement + " aXb " + replacement + " a.b",
)
def test_replacement_backreference_text_stays_literal(self):
self.assertEqual(replace_literal("[x]", "[x]", r"\g<0>\n"), r"\g<0>\n")
def test_no_match_returns_original_text(self):
self.assertEqual(find_literal_spans("aXb", "a.b"), [])
self.assertEqual(replace_literal("aXb", "a.b", "new"), "aXb")
def test_search_bounds(self):
for text, needle in (("abc", ""), ("x" * 4097, "x"), ("abc", "x" * 65)):
with self.subTest(lengths=(len(text), len(needle))), self.assertRaises(ValueError):
find_literal_spans(text, needle)
def test_replacement_bounds(self):
for limit in (0, -1, 11, 1.5, True):
with self.subTest(limit=limit), self.assertRaises(ValueError):
replace_literal("x", "x", "new", limit=limit)
with self.assertRaises(ValueError):
replace_literal("x", "x", "y" * 129)
def test_bounds_are_inclusive(self):
self.assertEqual(len(find_literal_spans("x" * 4096, "x")), 4096)
self.assertEqual(find_literal_spans("x" * 64, "x" * 64), [(0, 64)])
self.assertEqual(replace_literal("x" * 11, "x", "y", limit=10), "y" * 10 + "x")
if __name__ == "__main__":
unittest.main()
Treat reported passing counts as evidence for the checked cases and runtime only. They do not establish that every possible input was tested, that an application integrated the helper correctly, or that the specification matches the warehouse’s actual needs. The fixtures here are author-created teaching examples and require project-specific review before adoption.
Keep accepted fixtures immutable during candidate evaluation. A model may propose new cases in a separate list, but only the responsible reviewer should change expected outcomes. The DeepSeek regression-testing workflow is useful when a small validator becomes part of a larger change-review process.
Use failed cases to ask better follow-up questions
When a case fails, provide the smallest reproducing input, the expected decision or fields, the actual result, the pattern, flags, and runtime. Ask for a diagnosis before requesting a replacement. This prevents a series of broad rewrites from obscuring the original mistake.
The next author-created prompt is designed for a concrete failure report. Its placeholders are intentional; fill them with observations from your own runner. Do not present an assistant’s prediction as an executed result.
Review this failed check without changing the contract or fixtures.
Contract: [paste the approved contract]
Runtime and engine: [exact version]
Candidate pattern and flags: [exact values]
Wrapper and operation: [minimal relevant code]
Input, escaped: [repr-style value]
Expected decision and captures: [reviewer-owned expectation]
Observed result: [actual local test output]
Explain the likely cause and identify the responsible layer:
pattern, matching API, flags, preprocessing, escaping, or test harness.
Propose the smallest correction. List which existing cases could
change behavior. Suggest additional regression cases separately.
Do not remove a failing case or relabel its expected result.
If the input contains a final newline and the proposed fix adds trimming, compare that proposal with the contract. Trimming would introduce a new accepted input path. The appropriate correction might instead be the matching operation, or the expected outcome might need a deliberate product decision. Keep the distinction visible.
After a repair, run the entire suite rather than only the case that prompted it. A suffix fix can break the no-size branch; an escaping fix can alter a literal-search helper. Preserve the old failure as a regression case, along with a short explanation of what it protects.
Make Unicode and normalization product decisions
The word “digit” is insufficient for an ASCII-only contract. Python’s default Unicode string patterns let the shorthand digit class include decimal digits beyond ASCII. The explicit range used here keeps the intended alphabet visible. Similar care is needed whenever a shorthand class is wider than the business rule.
Challenge the example with full-width Latin letters, non-ASCII decimal digits, and a typographic dash in place of the ASCII hyphen. These values may look familiar to a person reading a form, but this contract rejects them. An error message can explain the accepted format without silently rewriting what the user supplied.
Unicode normalization also deserves an explicit decision. Python exposes canonical and compatibility normalization forms through its Unicode database module. Different forms have different purposes; a blanket instruction to “normalize Unicode” leaves the policy incomplete.
For this tutorial, every normalization step is excluded. If a future form intentionally accepts some alternative representations, specify the transformation first, then validate its output. Record whether the original value is retained, what the user sees, and whether two different submissions become the same stored identifier.
That last question matters in operational systems. If two inputs collapse to one canonical value, uniqueness checks and audit records must agree about identity. The regex cannot settle that design issue. Create tests for the transformation and the validator separately, followed by an end-to-end test for their composition.
Resist adding case-insensitive matching simply to make the form friendlier. The stated prefix rule requires uppercase ASCII. A more forgiving interface might display a suggested correction for confirmation, but that is a new interaction with its own expected behavior.
Record the runtime, dialect, and flags
A regex is interpreted within a particular engine. When moving this workflow to a browser, database, editor, or another programming language, preserve the contract and rewrite the implementation as needed. Named-group notation, flags, supported constructs, and replacement syntax are all things to verify in that engine’s documentation.
Do not describe a pattern as portable merely because it compiles in two places. Replay the same decision fixtures and expected captures in both runtimes. For an extraction tool, compare spans and ordering too. For replacement, compare the complete resulting text and the number of changes.
The stock-code candidate requires no optional matching flags. Make that choice explicit in review. Adding case-insensitive mode would conflict with its contract; adding a flag “just in case” creates another variable for future maintainers to investigate.
Pin the runtime in the reproducible test environment, and record the version actually used for a test report. Documentation may describe a newer release than your deployment. Before adopting an unfamiliar construct from an assistant’s answer, check that your deployed engine supports it.
A migration is also an opportunity to compare wrapper behavior. One service might raise an error for non-string input while another returns a failed validation result. Choose the intended interface deliberately and keep compatibility tests at the service boundary.
Track escaping through every representation
Patterns often travel through more than one string format. The value passed to an engine is distinct from the way it is written in Python source or serialized into JSON. Python’s regex HOWTO explains why raw string literals are commonly useful when a pattern contains backslashes.
Consider a separate literal-search example for a dotted release label. To make the period literal, the pattern value includes a backslash before it. In Python source, a raw string keeps that spelling easy to read. JSON has its own quoting rules, so use the serializer rather than manually counting backslashes.
import json
pattern_value = r"build\.7"
serialized = json.dumps({"pattern": pattern_value})
restored = json.loads(serialized)["pattern"]
assert restored == pattern_value
# JSON text contains: {"pattern": "build\\.7"}
The round-trip assertion checks the boundary you actually control. Add a behavioral check after decoding, so a correctly transported but wrongly chosen pattern still fails review. Serialization fidelity and matching correctness answer separate questions.
The main stock-code expression contains no backslashes, which simplifies this example’s transport. You should still preserve its exact value rather than applying generic unescaping routines to every model response. An extra decoding pass can change valid content and make a stored pattern differ from the one reviewers inspected.
When asking DeepSeek for machine-readable output, distinguish the pattern value from a language-specific source literal. Tell it which representation you need. Requesting “the escaped regex” without naming the destination invites confusion between JSON escaping, Python source escaping, and escaping literal user text for regex syntax.
Review untrusted candidates before executing them
Treat a newly proposed expression and any accompanying script as untrusted input to your review process. First read the pattern for unnecessary complexity and read the script for unrelated actions. There is no need for a stock-code validator to access a network, inspect credentials, install packages, or open arbitrary files.
For the small candidate here, check the fixed character classes, exact repetition counts, optional suffix, and full-match call before running the bounded fixtures. For a substantially larger candidate, require a clearer explanation and consider simplifying the requirement into several explicit checks.
Keep the assistant’s role constrained when automated tooling is involved. Let it propose a patch or candidate value for review. Do not give generated text an automatic path into a long-lived production process merely because the response also contains a reassuring explanation.
The third author-created prompt focuses on static review. It asks for a reasoned assessment without requesting execution of suspicious expressions or manufactured performance numbers.
Statically review this regex candidate and wrapper.
Do not execute the candidate or generate a stress-test payload.
Contract: [approved rules]
Engine, version, and flags: [exact environment]
Candidate and wrapper: [code under review]
Input and pattern limits: [current bounds]
Identify unnecessary constructs, ambiguous repeated alternatives,
unbounded repetition, hidden preprocessing, and unsupported assumptions.
Explain each concern using the contract and code. Suggest a simpler
implementation, including a literal operation or parser where useful.
Separate observed code facts from risks that require further evaluation.
Do not certify the expression as safe or claim benchmark results.
A static review can reveal a dangerous design or a missing bound, but a clean-looking review is not a security certificate. Apply the same DeepSeek code-review discipline to the wrapper, callers, tests, and deployment path.
Handle ReDoS with bounded, isolated evaluation
OWASP describes regular expression denial of service as a risk when certain expressions consume excessive work on crafted input. Repeated groups containing repetition or overlapping alternatives are warning signs in backtracking engines. A candidate can look concise while creating a difficult failure path.
You do not need to execute a deliberately harmful expression to understand the review requirement. Stop at static inspection when a candidate is suspicious. Ask for a simpler form, consult an engine-aware reviewer, or move evaluation into a dedicated isolated process with enforced limits.
Set bounds for both the input and the pattern before compilation. Limit the number of cases and concurrent evaluations as well. A small input limit cannot justify accepting an arbitrarily large expression, and a short expression cannot justify feeding it an unlimited stream of text.
For untrusted patterns, isolate compilation and matching from the application process. Use an external supervisor capable of terminating the worker, with a wall-clock deadline and appropriate CPU and memory limits. A timer that merely records how long a call took does not stop that call from monopolizing a worker.
The permitted values here have only seven or nine characters, and the candidate contains fixed-width pieces with one short optional suffix. Those design choices make this teaching example straightforward to inspect. They do not justify reusing its execution setup for arbitrary expressions generated for unrelated tasks.
Engine selection can change the available tradeoffs. The RE2 project documents linear matching time in input length and a configurable memory budget, while deliberately omitting constructs such as backreferences and lookaround. Those properties are worth evaluating when accepting user-supplied patterns, alongside syntax compatibility and application requirements.
Do not turn that engine property into an unlimited-resource promise for an entire service. Bound request sizes, compilation frequency, total work, and response sizes. Record timeouts and rejected evaluations as outcomes requiring investigation, rather than silently rerunning them with larger limits.
Know when a literal operation or parser is clearer
Ask what the application needs before committing to regex. Finding a fixed substring, checking a fixed prefix, or replacing a known literal may be clearest with ordinary string methods. A pattern becomes useful when it expresses variable structure more clearly than the alternatives.
This stock-code rule can also be implemented by checking length, separator positions, character membership, and the optional size. That direct implementation is useful as a separate reference for tests. It may even be the better production choice if teammates find it easier to review or need precise error messages.
For example, an interface may need to tell a user that the prefix has the wrong case, the numeric section has the wrong width, or the size is unsupported. A single successful-or-failed match gives little guidance by itself. Explicit staged checks can align naturally with those messages.
Choose a format-aware parser when the input has nesting, escaping, quoting, or a grammar already handled by a trusted library. JSON data should be decoded as JSON before individual fields are validated. A CSV import should respect the file format’s quoting rules before asking whether a selected cell contains a stock code.
There is still useful work for DeepSeek in those cases. Ask it to compare a direct implementation, a parser-based approach, and a regex against maintenance needs and error behavior. Require it to identify additional dependencies and unsupported assumptions. Choose the smallest solution whose behavior your team can explain.
Release the behavior with the expression
The release artifact should include the contract, candidate, wrapper, fixed cases, and the recorded environment. Keep them close enough that a future change cannot easily update one while overlooking the others. A one-line pattern pasted into a configuration file leaves too much of the original reasoning behind.
Before adopting the example in an application, use this checklist as a review agenda:
- Ownership: a responsible reviewer has approved the allowed values, missing-size representation, and handling of invalid types
- Operation: the deployed caller validates the full original input and does not silently search, trim, normalize, or case-convert
- Outputs: exact field names, strings, leading zeros, and absent values are covered by assertions
- Boundaries: both valid lengths, nearby invalid lengths, unwanted suffixes, whitespace, newlines, and Unicode near misses are represented
- Environment: the tested engine, runtime, flags, serialized value, and deployment configuration agree
- Resources: input bounds are enforced, and any broader untrusted-pattern evaluation has separate process and resource limits
- Integration: actual callers handle rejection and exceptions correctly, with a tested path back to the previous behavior
After deployment, use aggregate rejection reasons where practical rather than collecting complete user input by default. A sudden change in rejected values may reveal an upstream format change or a mistaken contract. Investigate it before widening the expression, and avoid treating every rejected submission as evidence that validation should become more permissive.
When the rules genuinely change, version the decision and add examples that demonstrate the new behavior. Review any migration of stored data separately. This keeps an apparently small regex edit from silently changing what the system considers a valid identifier.

Common questions
Can DeepSeek generate the tests as well?
It can suggest cases, explain gaps, and draft test code. Keep those suggestions separate from the accepted fixture set until reviewed. If the same assistant chooses the implementation and redefines every expected outcome, agreement between them provides little independent evidence.
Does passing the supplied suite prove the regex is correct?
It establishes agreement with those checks in that recorded environment. Confidence also depends on the contract, independent review, case coverage, wrapper behavior, and integration tests. The suite is a useful starting point for this fictional format, not proof about an unseen production system.
Should every regex come with a long explanation?
The explanation should be proportional to the decision. This small validator needs a readable contract and a brief component review. If understanding a candidate requires pages of exceptions, consider splitting the task into explicit checks or selecting a parser that already models the format.
What to take into your next regex task
Write the acceptance rules before requesting a pattern. Use DeepSeek to propose and explain a candidate, then compare the implementation with examples whose expectations remain under reviewer control. Check captures as carefully as acceptance, keep normalization explicit, and test the exact runtime and representation that will ship.
A useful result is a small package of reproducible behavior: the rule, its implementation, the cases that challenge it, and a clear account of what was actually checked. That package is easier to review, maintain, and change than an isolated expression copied from a conversation.
Sources & References
Official documentation supports the language and engine details. The stock-code contract, prompt templates, examples, and review workflow are original teaching material.
- Python regular expression reference: matching operations, groups, character classes, flags, escaping, and replacement behavior
- Python regular expression HOWTO: source-string escaping and choosing simple string operations
- Python JSON encoder and decoder documentation: serializing and restoring pattern strings
- Python Unicode database documentation: available normalization forms
- OWASP regular expression denial of service guidance: backtracking risk and suspicious repeated structures
- RE2 project documentation: engine guarantees, memory budget, and unsupported constructs
- DeepSeek API documentation: official starting point if you choose to automate the prompting workflow
