# Regex Lab 🧪 — Regex Tester & Validator (`perryay/regex-lab`) Actor

Interactive regex testing tool supporting findall, match, search, split, and sub (replace) modes. Test patterns against sample text, view full match details, capture groups, named groups, and detailed error messages for invalid patterns.

- **URL**: https://apify.com/perryay/regex-lab.md
- **Developed by:** [Perry AY](https://apify.com/perryay) (community)
- **Categories:** Developer tools
- **Stats:** 2 total users, 1 monthly users, 50.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.008 / actor start

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js/docs.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python/docs.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

## Regex Lab 🧪 — Regex Tester, Validator & Debugger

**Test regular expressions against sample text with 5 operation modes, capture group extraction, named group support, flag configuration, and comprehensive error reporting.**

Regular expressions are powerful but notoriously difficult to get right. A single misplaced metacharacter can turn a working pattern into a silent failure. **Regex Lab** gives you a structured debugging environment: compile your pattern, run it against test text in one of five modes, and inspect every detail of the result — match positions, capture groups, named groups, and syntax errors with precise line and column numbers.

Choose from `findall` (all non-overlapping matches), `match` (match from the start of the string), `search` (first match anywhere), `split` (divide text into parts at each match), or `sub` (replace matches with placeholder text). Configure any combination of regex flags (`i` ignorecase, `m` multiline, `s` dotall, `x` verbose, `u` unicode, `a` ascii). Named capture groups using `(?P<name>...)` syntax are fully supported with automatic detection and extraction.

---

### ✨ Features

- **5 operation modes** — `findall` returns all non-overlapping matches, `match` checks from the start of the string, `search` finds the first match anywhere, `split` divides text at match boundaries, and `sub` replaces matches with configurable text
- **Named capture group support** — Full support for Python regex named groups (`(?P<name>...)` syntax) with automatic detection, extraction, and groupdict output
- **Regex flag configuration** — Combine any of 6 regex flags: `i` (IGNORECASE), `m` (MULTILINE), `s` (DOTALL), `x` (VERBOSE), `u` (UNICODE), `a` (ASCII) — passed as a simple string like `"ims"`
- **Detailed match information** — Every match includes the matched text, start and end positions (span), and capture group values — enabling precise debugging of complex patterns
- **Syntax error reporting** — Invalid patterns return an error object with the error message, and when available, the exact position, line number, and column number of the syntax error
- **Pattern metadata** — Each result includes total group count, named group keys, and whether named groups are present — helpful for understanding pattern structure at a glance
- **Memory-safe output** — Match details are limited to 100 entries to prevent excessive output sizes, while the full results arrays can contain any number of matches
- **Zero configuration** — No setup, no databases, no dependencies beyond the pattern and text. Just send your regex and see the results

### 🚀 Quick Start

#### Find All Matches (`findall`)

**Input:**
```json
{
  "pattern": "\\d+",
  "text": "Contact: 555-1234, 555-5678\nOrders: #A100, #B200",
  "mode": "findall"
}
````

**Response:**

```json
{
  "pattern": "\\d+",
  "flags": "",
  "mode": "findall",
  "text_length": 50,
  "groups": 0,
  "named_groups": [],
  "has_named_groups": false,
  "matches": ["555", "1234", "555", "5678", "100", "200"],
  "count": 6,
  "match_details": [
    { "text": "555", "span": [23, 26] },
    { "text": "1234", "span": [27, 31] },
    { "text": "555", "span": [33, 36] },
    { "text": "5678", "span": [37, 41] },
    { "text": "100", "span": [51, 54] },
    { "text": "200", "span": [57, 60] }
  ]
}
```

#### Search with Named Groups (`search`)

**Input:**

```json
{
  "pattern": "Hello (?P<name>\\w+)",
  "text": "Hello world! Hello regex!",
  "mode": "search"
}
```

**Response:**

```json
{
  "pattern": "Hello (?P<name>\\w+)",
  "flags": "",
  "mode": "search",
  "text_length": 24,
  "groups": 1,
  "named_groups": ["name"],
  "has_named_groups": true,
  "matched": true,
  "span": [0, 11],
  "matched_text": "Hello world",
  "groups": ["world"],
  "groupdict": { "name": "world" }
}
```

#### Replace Matches (`sub`)

**Input:**

```json
{
  "pattern": "\\d{3}-\\d{4}",
  "text": "Call 555-1234 or 555-5678 for help.",
  "mode": "sub"
}
```

**Response:**

```json
{
  "pattern": "\\d{3}-\\d{4}",
  "flags": "",
  "mode": "sub",
  "text_length": 40,
  "groups": 0,
  "named_groups": [],
  "has_named_groups": false,
  "replacement": "***",
  "new_text": "Call *** or *** for help.",
  "replacements": 2
}
```

#### Split Text (`split`)

**Input:**

```json
{
  "pattern": "[,\\s]+",
  "text": "apple, banana, cherry, date",
  "mode": "split"
}
```

**Response:**

```json
{
  "pattern": "[,\\s]+",
  "flags": "",
  "mode": "split",
  "text_length": 26,
  "groups": 0,
  "named_groups": [],
  "has_named_groups": false,
  "parts": ["apple", "banana", "cherry", "date"],
  "count": 4
}
```

#### Match from Start (`match`)

**Input:**

```json
{
  "pattern": "\\d{3}",
  "text": "123-456-7890",
  "mode": "match"
}
```

**Response:**

```json
{
  "pattern": "\\d{3}",
  "flags": "",
  "mode": "match",
  "text_length": 11,
  "groups": 0,
  "named_groups": [],
  "has_named_groups": false,
  "matched": true,
  "span": [0, 3],
  "matched_text": "123",
  "groups": [],
  "groupdict": {}
}
```

#### Invalid Pattern — Error Reporting

**Input:**

```json
{
  "pattern": "[unclosed",
  "text": "test",
  "mode": "findall"
}
```

**Response:**

```json
{
  "pattern": "[unclosed",
  "flags": "",
  "mode": "findall",
  "text_length": 4,
  "error": {
    "message": "unterminated character set at position 0",
    "pos": 0,
    "lineno": 1,
    "colno": 1
  }
}
```

### 📋 Input Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `pattern` | string | *(required)* | Regular expression pattern to compile and test. Should be a valid Python regex. |
| `text` | string | *(required)* | Sample text to test the pattern against. |
| `mode` | string | `"findall"` | Operation mode: `findall`, `match`, `search`, `split`, or `sub`. |
| `flags` | string | `""` | Regex flag characters. Combine any of: `i` (ignorecase), `m` (multiline), `s` (dotall), `x` (verbose), `u` (unicode), `a` (ascii). |

#### Operation Modes

| Mode | Description | Output |
|------|-------------|--------|
| `findall` | Find all non-overlapping matches of the pattern in the text | Array of match strings, count, and match detail with span positions |
| `match` | Check if the pattern matches from the very beginning of the text | Boolean `matched`, span, matched text, groups, and groupdict |
| `search` | Find the first occurrence of the pattern anywhere in the text | Boolean `matched`, span, matched text, groups, and groupdict |
| `split` | Split the text into parts at each match boundary | Array of parts and count |
| `sub` | Replace all matches with placeholder text (`***`) | New text string and replacement count |

#### Regex Flags

| Flag Character | Python Flag | Effect |
|---------------|-------------|--------|
| `i` | `re.IGNORECASE` | Perform case-insensitive matching |
| `m` | `re.MULTILINE` | `^` and `$` match start/end of each line (not just string) |
| `s` | `re.DOTALL` | `.` matches any character including newline |
| `x` | `re.VERBOSE` | Allow whitespace and comments in pattern for readability |
| `u` | `re.UNICODE` | Unicode matching (Python 3 default) |
| `a` | `re.ASCII` | Restrict `\w`, `\d`, `\b`, etc. to ASCII-only matching |

### 📤 Output Format

#### Common Fields (all modes)

| Field | Type | Description |
|-------|------|-------------|
| `pattern` | string | The regex pattern that was tested |
| `flags` | string | The flag characters that were applied |
| `mode` | string | The operation mode used |
| `text_length` | integer | Length of the test text in characters |
| `groups` | integer | Number of capture groups in the pattern |
| `named_groups` | array | List of named group keys (e.g., `["name", "email"]`) |
| `has_named_groups` | boolean | Whether the pattern contains named capture groups |
| `error` | object | Error object (only present on compile errors): `message`, `pos`, `lineno`, `colno` |

#### Mode-Specific Fields

##### `findall` Mode

| Field | Type | Description |
|-------|------|-------------|
| `matches` | array | Array of all matched strings (flattened if multiple groups). Limited to practical output size. |
| `count` | integer | Total number of matches found |
| `match_details` | array | Array of detail objects with `text` (matched string) and `span` (start/end positions). Limited to 100 entries. |

##### `match` and `search` Modes

| Field | Type | Description |
|-------|------|-------------|
| `matched` | boolean | Whether a match was found |
| `span` | array | Start and end positions of the match: `[start, end]` |
| `matched_text` | string | The text that was matched |
| `groups` | array | Tuple of captured group values (empty if no groups) |
| `groupdict` | object | Dictionary of named group values (empty if no named groups) |

##### `split` Mode

| Field | Type | Description |
|-------|------|-------------|
| `parts` | array | Array of text parts after splitting |
| `count` | integer | Number of parts |

##### `sub` Mode

| Field | Type | Description |
|-------|------|-------------|
| `replacement` | string | The replacement string used (`"***"`) |
| `new_text` | string | The text after all replacements |
| `replacements` | integer | Number of replacements performed |

### 📖 Usage Examples

#### cURL (Apify API)

```bash
## Find all email addresses
curl -X POST "https://api.apify.com/v2/acts/perryay~regex-lab/runs" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -d '{
    "pattern": "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}",
    "text": "Contact us at support@example.com or sales@example.org",
    "mode": "findall"
  }'

## Case-insensitive search
curl -X POST "https://api.apify.com/v2/acts/perryay~regex-lab/runs" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -d '{
    "pattern": "hello",
    "text": "Hello World! hello again! HELLO!",
    "mode": "findall",
    "flags": "i"
  }'
```

#### Python (Apify SDK)

```python
from apify_client import ApifyClient

client = ApifyClient("YOUR_API_TOKEN")

## Test a regex pattern
result = client.actor("perryay~regex-lab").call(
    run_input={
        "pattern": r"\b[A-Z][a-z]+\b",
        "text": "Alice and Bob went to Paris. Charlie stayed home.",
        "mode": "findall",
    }
)
dataset = client.dataset(result["defaultDatasetId"]).list_items()
for item in dataset.items:
    if item.get("error"):
        err = item["error"]
        print(f"Regex Error at line {err['lineno']}, col {err['colno']}: {err['message']}")
    else:
        print(f"Pattern: {item['pattern']}")
        print(f"Mode: {item['mode']}")
        print(f"Groups: {item['groups']}, Named groups: {item['named_groups']}")
        for m in item.get("match_details", []):
            print(f"  Match '{m['text']}' at position {m['span']}")
        print(f"Total matches: {item.get('count', 0)}")
```

#### JavaScript / Node.js (Apify SDK)

```javascript
import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: 'YOUR_API_TOKEN' });

const result = await client.actor('perryay~regex-lab').call({
  pattern: '(\\w+)@(\\w+)\\.(\\w+)',
  text: 'user@example.com',
  mode: 'search',
});

const { items } = await client.dataset(result.defaultDatasetId).listItems();
for (const item of items) {
  if (item.matched) {
    console.log(`Matched: ${item.matched_text} (position ${item.span})`);
    console.log(`Groups: ${item.groups}`);
  }
}
```

### 🎯 Use Cases

- **Regex development and debugging** — Quickly test and iterate on patterns during development without setting up a local Python environment or firing up an interactive shell. See exactly what matches, where, and what groups are captured.
- **Data extraction pipeline prototyping** — Before coding a production data extraction pipeline, use Regex Lab to validate that your pattern correctly extracts fields from sample data. Switch between `findall` and `search` modes to compare behavior.
- **Log parsing pattern design** — Design and test regex patterns for extracting structured data from unstructured log lines (Apache/Nginx access logs, syslog, application logs) before deploying into your log aggregation pipeline.
- **Text sanitization and redaction** — Use `sub` mode to validate that your redaction patterns correctly replace sensitive data (phone numbers, email addresses, credit card numbers) in sample text before rolling out to production pipelines.
- **Input validation pattern testing** — Verify that regex patterns intended for form validation, URL routing, or data quality checks behave correctly with valid inputs, edge cases, and malicious payloads.
- **Migration pattern validation** — When migrating data between systems, test regex patterns for field extraction, value transformation, and format conversion against sample records before running full-scale migration.
- **Educational demonstrations** — Use Regex Lab to teach regex concepts interactively: show how flags change behavior, how capture groups extract sub-matches, and how the different operation modes compare.
- **CI/CD pipeline integration** — Automate regex validation as part of your build pipeline. Test critical patterns against known-good and known-bad inputs, and fail the build if expected matches aren't found or unexpected matches appear.

### ❓ FAQ

**Q: What regex engine does this use?**
A: Python's `re` module, which implements Perl-compatible regex with some Python-specific extensions. It supports all standard features: character classes, quantifiers, alternation, groups, lookahead/lookbehind, backreferences, and named groups.

**Q: Are lookahead and lookbehind assertions supported?**
A: Yes. Python's `re` module supports positive lookahead (`(?=...)`), negative lookahead (`(?!...)`), positive lookbehind (`(?<=...)`), and negative lookbehind (`(?<!...)`). Variable-length lookbehind is supported in Python 3.x (unlike some other regex engines).

**Q: What is the difference between `match` and `search` modes?**
A: `match` checks if the pattern matches starting at position 0 of the text (the beginning). `search` scans through the entire text and returns the first match anywhere. If you want to find all occurrences, use `findall`.

**Q: How are named capture groups displayed?**
A: Named groups (defined with `(?P<name>...)` syntax) are listed in the `named_groups` array. In `match` and `search` modes, their values appear in the `groupdict` object. The `groups` field shows the total count of both named and unnamed capture groups.

**Q: What happens if my pattern is invalid?**
A: The actor returns an `error` object with the Python regex error message, and when available, the exact character position (`pos`), line number (`lineno`), and column number (`colno`) where the error occurred. This makes debugging invalid patterns straightforward.

**Q: What does `sub` mode use as the replacement text?**
A: By default, `sub` mode replaces all matches with `"***"`. The replacement text is fixed and cannot be customized in the current version. Use `sub` mode to verify that your pattern correctly identifies all intended matches and to see the transformation result.

**Q: Are backreferences supported in the pattern?**
A: Yes. Backreferences (`\1`, `\2`, etc.) and named backreferences (`(?P=name)`) are supported in the pattern itself. However, the replacement text in `sub` mode uses a fixed string (`***`) and does not currently support backreference expansion in the replacement.

**Q: Is there a limit on input text size?**
A: The actor processes text of any length, but match details are capped at 100 entries and the full matches array may be truncated for very long texts. This prevents excessive output sizes while still giving you complete match coverage.

**Q: Can I use this actor with binary or non-UTF-8 data?**
A: No. The actor expects string input. Binary data or encoded content should be decoded to a string before passing to the actor.

### 🛠 Tips & Best Practices

- **Start with `search` mode for pattern discovery** — When building a new pattern, use `search` mode first to confirm your pattern finds *something*. Once it matches, switch to `findall` to find all occurrences, then `match` to verify anchoring behavior.
- **Use `findall` with groups to extract structured data** — When you need to extract specific parts from each match (e.g., name, email, and domain separately), use capture groups in your pattern. The `matches` array will contain tuples of captured values for each match.
- **Test edge cases explicitly** — Always test your pattern against empty strings, very long strings, strings with special characters, strings with newlines (use flag `s` for dotall), and strings that should *not* match. The `text` field accepts any content.
- **Use verbose mode (`x`) for complex patterns** — Complex regex patterns can be hard to read. Add `x` to your flags and add whitespace and comments within the pattern for readability. The verbose flag ignores whitespace and allows inline comments with `#`.
- **Debug with span positions** — The `span` values (`[start, end]`) show the exact character positions of each match. Use these to verify your pattern isn't matching unexpected parts of the input. A span of `[6, 9]` means characters at indexes 6, 7, and 8 (zero-indexed).
- **Combine flags strategically** — Common flag combinations: `"i"` for case-insensitive search, `"im"` for case-insensitive multiline matching (useful for log parsing), `"is"` for case-insensitive dotall (match across lines). Test each combination to ensure expected behavior.
- **Remember to escape in JSON** — When sending patterns via the Apify API (JSON), backslashes must be escaped: `\d` becomes `\\d`, `\w+` becomes `\\w+`. If you're testing the actor from the Apify Console UI, the JSON editor handles this automatically.
- **Validate with `match` mode for strict inputs** — Use `match` mode when you need to validate that an entire string conforms to a pattern (e.g., a phone number field, an email format). `match` requires the pattern to match from the very beginning.

### 🧪 Pattern Development Workflow

A recommended workflow for developing regex patterns with Regex Lab:

```
1. Write initial pattern → call actor with search mode
     ↓
2. Match found?  ──YES──→  Check matched text and span
     ↓ NO                    ↓ correct
3. Fix pattern syntax        3. Switch to findall mode
   (use error position,        → check all matches
    line, column info)          ↓ correct
                                4. Add capture groups
                                   → test search mode for groups
                                    ↓ correct
                                    5. Test with expected non-matches
                                       → confirm no false positives
                                        ↓ validated
                                        6. Use in production pipeline
```

### ⚙️ Regex Feature Support

| Feature | Support | Example |
|---------|---------|---------|
| Character classes | ✅ | `[a-z]`, `[^0-9]` |
| Shorthand classes | ✅ | `\d`, `\w`, `\s`, `\D`, `\W`, `\S` |
| Quantifiers | ✅ | `+`, `*`, `?`, `{3}`, `{2,5}` |
| Greedy/lazy quantifiers | ✅ | `.*`, `.*?`, `.+?` |
| Alternation | ✅ | `cat\|dog\|bird` |
| Anchors | ✅ | `^`, `$`, `\b`, `\B` |
| Grouping | ✅ | `(...)`, `(?:...)` |
| Named groups | ✅ | `(?P<name>...)` |
| Backreferences | ✅ | `\1`, `\2`, `(?P=name)` |
| Lookahead | ✅ | `(?=...)`, `(?!...)` |
| Lookbehind | ✅ | `(?<=...)`, `(?<!...)` |
| Atomic groups | ✅ | `(?>...)` |
| Flags inline | ✅ | `(?i)`, `(?m)`, `(?s)` |
| Conditional patterns | ✅ | `(?(condition)yes\|no)` |

***

### 🔗 Related Tools

Check out other developer utilities by [perryay](https://apify.com/perryay):

| Tool | Description |
|------|-------------|
| [JSON Studio](https://apify.com/perryay/json-studio) | Format, validate, transform, and diff JSON data with 8 operation modes |
| [QR Craft](https://apify.com/perryay/qr-craft) | Generate high-quality QR codes in PNG or SVG, batch up to 50 |
| [UUID Lab](https://apify.com/perryay/uuid-lab) | Generate UUID v4/v7, NanoID, Short ID, and ULID identifiers |
| [Domain Intel](https://apify.com/perryay/domain-intel) | WHOIS, DNS, and SSL lookup for domain intelligence |
| [Meta Mate](https://apify.com/perryay/meta-mate) | Extract Open Graph, Twitter Cards, and JSON-LD metadata |
| [IP Geo](https://apify.com/perryay/ip-geo) | Multi-provider IP geolocation with ISP detection |
| [URL Health](https://apify.com/perryay/url-health) | Check URL accessibility, redirects, and SSL health |
| [PW Forge](https://apify.com/perryay/pw-forge) | Generate secure passwords with entropy calculation |
| [TZ Mate](https://apify.com/perryay/tz-mate) | Convert timezones and check DST offsets |
| [Regex Lab](https://apify.com/perryay/regex-lab) | Test and debug regular expressions online |
| [Brand Monitor Lite](https://apify.com/perryay/brand-monitor-lite) | Track brand mentions across multiple URLs |
| [Link Quality Analyzer](https://apify.com/perryay/link-quality-analyzer) | Detect broken links and audit link quality |
| [Mock Data Generator](https://apify.com/perryay/mock-data-generator) | Generate realistic test data for development |
| [HTML to Markdown](https://apify.com/perryay/html-to-markdown) | Convert web pages or HTML to clean Markdown |
| [SSL Cert Inspector](https://apify.com/perryay/ssl-cert-inspector) | Deep SSL/TLS certificate analysis with scoring |

# Actor input Schema

## `pattern` (type: `string`):

Regular expression pattern

## `text` (type: `string`):

Text to test the pattern against

## `flags` (type: `string`):

Regex flags (i=ignorecase, m=multiline, s=dotall, x=verbose)

## `mode` (type: `string`):

Search mode

## Actor input object example

```json
{
  "pattern": "\\d+",
  "text": "Contact: 555-1234, 555-5678\nOrders: #A100, #B200",
  "flags": "",
  "mode": "findall"
}
```

# Actor output Schema

## `results` (type: `string`):

Pattern test results in the default dataset

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "pattern": "\\d+",
    "text": `Contact: 555-1234, 555-5678
Orders: #A100, #B200`
};

// Run the Actor and wait for it to finish
const run = await client.actor("perryay/regex-lab").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "pattern": "\\d+",
    "text": """Contact: 555-1234, 555-5678
Orders: #A100, #B200""",
}

# Run the Actor and wait for it to finish
run = client.actor("perryay/regex-lab").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "pattern": "\\\\d+",
  "text": "Contact: 555-1234, 555-5678\\nOrders: #A100, #B200"
}' |
apify call perryay/regex-lab --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=perryay/regex-lab",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "Regex Lab 🧪 — Regex Tester & Validator",
        "description": "Interactive regex testing tool supporting findall, match, search, split, and sub (replace) modes. Test patterns against sample text, view full match details, capture groups, named groups, and detailed error messages for invalid patterns.",
        "version": "1.0",
        "x-build-id": "gSRxwBz3gRr8NVgW1"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/perryay~regex-lab/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-perryay-regex-lab",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/perryay~regex-lab/runs": {
            "post": {
                "operationId": "runs-sync-perryay-regex-lab",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/perryay~regex-lab/run-sync": {
            "post": {
                "operationId": "run-sync-perryay-regex-lab",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "required": [
                    "pattern",
                    "text"
                ],
                "properties": {
                    "pattern": {
                        "title": "Regex Pattern",
                        "type": "string",
                        "description": "Regular expression pattern"
                    },
                    "text": {
                        "title": "Test Text",
                        "type": "string",
                        "description": "Text to test the pattern against"
                    },
                    "flags": {
                        "title": "Flags",
                        "type": "string",
                        "description": "Regex flags (i=ignorecase, m=multiline, s=dotall, x=verbose)",
                        "default": ""
                    },
                    "mode": {
                        "title": "Mode",
                        "enum": [
                            "findall",
                            "match",
                            "search",
                            "split",
                            "sub"
                        ],
                        "type": "string",
                        "description": "Search mode",
                        "default": "findall"
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
