What Regex Patterns Are Supported by needle.Field?
needle.Field accepts any Python-compatible regular expression through its pattern argument, passing it directly to Python's standard re module for validation.
In the cactus-compute/needle repository, the Field class provides schema-based validation for tool arguments. The pattern parameter stores a regex string in the generated JSON-Schema, which the runtime later enforces using re.match(pattern, value). This design means you have access to Python's full regex engine without artificial limitations.
Where the Pattern Is Stored and Used
The Field class definition in [needle/agent/tools.py (lines 18–31)](https://github.com/cactus-compute/needle/blob/main/needle/agent/tools.py#L18-L31) captures the pattern argument and incorporates it into the schema:
# From needle/agent/tools.py
def Field(
*,
pattern: str | None = None,
# ... other parameters
) -> FieldInfo:
"""Define constraints for a tool parameter."""
At runtime, validation occurs through standard re.match calls. The test suite in [tests/test_environments.py (lines 55–56)](https://github.com/cactus-compute/needle/blob/main/tests/test_environments.py#L55-L56) demonstrates this pattern matching in action.
Supported Regex Features
Because needle.Field delegates to Python's re module, you can use any feature the engine supports:
- Anchors:
^(start),$(end) — e.g.,^[a-z]+$for lowercase-only strings - Character classes:
[0-9],[\w.-],[a-zA-Z] - Quantifiers:
*(zero or more),+(one or more),{m,n}(range) - Optional elements:
?— e.g.,^\+?for optional leading plus sign - Escapes:
\\.for literal dots,\\dfor digits,\\wfor word characters - Whitespace and hyphens:
[0-9 -]matches digits, spaces, or hyphens - Unicode support:
(?u)flag orre.UNICODEbehavior by default - Case-insensitive matching:
(?i)prefix — e.g.,(?i)yes|no
Practical Code Examples
Validating Lowercase Names
import needle
@needle.tool
def greet(name: str = needle.Field(pattern="^[a-z]+$", min_length=2)):
"""Greet someone with a lowercase-only name."""
return {"msg": f"Hello, {name}!"}
- Valid:
greet("alice")→ succeeds - Invalid:
greet("Alice")→ fails (uppercase "A" violates^[a-z]+$)
Phone Number Validation
This pattern appears in [needle/environments/data_capture.py](https://github.com/cactus-compute/needle/blob/main/needle/environments/data_capture.py):
from typing import Optional, Annotated
import needle
class Capture:
phone: Optional[
Annotated[str, needle.Field(pattern=r"^\+?[0-9][0-9 -]{5,17}$")]
] = None
- Accepts:
"+1 555-1234","5551234567","+44 20 7946 0958" - Rejects:
"abc123"(letters not permitted),"123"(too short)
Email Pattern with Format Hint
@needle.tool
def register(
email: str = needle.Field(
pattern=r"^[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,}$",
format="email"
)
):
"""Register with a validated email address."""
return {"status": "ok"}
The format="email" parameter adds JSON-Schema metadata but does not affect regex validation.
Testing Your Patterns
The test suite in [tests/test_tools.py (lines 65–74)](https://github.com/cactus-compute/needle/blob/main/tests/test_tools.py#L65-L74) validates that patterns are correctly stored and enforced:
# From tests/test_tools.py
def test_field_pattern():
field = needle.Field(pattern="^[a-z]+$")
assert field.pattern == "^[a-z]+$"
When writing your own patterns, test them directly with re before applying them:
import re
pattern = r"^\+?[0-9][0-9 -]{5,17}$"
test_values = ["+1 555-1234", "5551234567", "abc123"]
for val in test_values:
match = re.match(pattern, val)
print(f"{val!r}: {'✓' if match else '✗'}")
Key Source Files
| File | Purpose |
|---|---|
needle/agent/tools.py |
Field class implementation and schema building |
tests/test_tools.py |
Unit tests demonstrating supported patterns |
tests/test_environments.py |
Runtime validation with re.match |
needle/environments/data_capture.py |
Production examples of complex patterns |
Summary
needle.Field(pattern=...)accepts any Pythonre-compatible regular expression- The pattern is stored verbatim in JSON-Schema and validated with
re.match() - Full Python regex syntax is supported: anchors, classes, quantifiers, flags, and escapes
- Test patterns with the standard
remodule before deployment - Reference implementation lives in
needle/agent/tools.py
Frequently Asked Questions
Does needle.Field support PCRE or JavaScript regex syntax?
No. needle.Field specifically uses Python's re module. While many features overlap with PCRE and JavaScript engines, Python-specific constructs like (?P<name>...) named groups work, but JavaScript-only features like lookbehind assertions with variable-length patterns may behave differently.
Can I use regex flags like re.IGNORECASE?
Yes. Embed flags directly in the pattern string using the (?i), (?m), (?s), or (?u) syntax. For case-insensitive matching, use (?i)pattern rather than the re.IGNORECASE constant, since needle.Field receives a string rather than a compiled regex object.
What happens when a pattern fails to match?
The validation logic in needle rejects the argument and typically raises a validation error indicating which parameter failed and what pattern was expected. The exact error format depends on your environment's error handling configuration.
Are there performance limits on pattern complexity?
needle.Field imposes no explicit limits. However, extremely complex patterns or those with catastrophic backtracking (nested quantifiers like (a+)+) can cause performance issues during validation. Test patterns against edge-case inputs to ensure acceptable runtime behavior.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →