## Name

Data::Random::String::Matches - Generate random strings matching a regex

## Synopsis

```perl
    use Data::Random::String::Matches;

    # Create a generator with regex and optional length
    my $gen = Data::Random::String::Matches->new(qr/[A-Z]{3}\d{4}/, 7);

    # Generate a matching string
    my $str = $gen->generate();
    print $str;  # e.g., "XYZ1234"

    # Alternation
    my $gen2 = Data::Random::String::Matches->new(qr/(cat|dog|bird)/);
    my $animal = $gen2->generate_smart();  # "cat", "dog", or "bird"

    # Backreferences
    my $gen3 = Data::Random::String::Matches->new(qr/(\w{3})-\1/);
    my $str3 = $gen3->generate_smart();  # e.g., "abc-abc"

    # Groups and quantifiers
    my $gen4 = Data::Random::String::Matches->new(qr/(ha){2,4}/);
    my $laugh = $gen4->generate_smart();  # "haha", "hahaha", or "hahahaha"

    # Unicode
    $gen = Data::Random::String::Matches->new(qr/\p{L}{5}/);

    # Named captures
    $gen = Data::Random::String::Matches->new(qr/(?<year>\d{4})-\k<year>/);

    # Possessive
    $gen = Data::Random::String::Matches->new(qr/\d++[A-Z]/);

    # Lookaheads
    $gen = Data::Random::String::Matches->new(qr/\d{3}(?=[A-Z])/);

    # Combined
    $gen = Data::Random::String::Matches->new(
            qr/(?<prefix>\p{Lu}{2})\d++\k<prefix>(?=[A-Z])/
    );

    # Consistency with Legacy software
    print Data::Random::String::Matches->create_random_string(length => 3, regex => '\d{3}'), "\n";
```

## Description

This module generates random strings that match a given regular expression pattern.
It parses the regex pattern and intelligently builds matching strings, supporting
a wide range of regex features.

## Supported Regex Features

### Character Classes

- Basic classes: `[a-z]`, `[A-Z]`, `[0-9]`, `[abc]`
- Negated classes: `[^a-z]`
- Ranges: `[a-zA-Z0-9]`
- Escape sequences in classes: `[\d\w]`
- POSIX classes: `[[:digit:]]`, `[[:^alpha:]]`
- Punctuation, a `-` at either end and a `]` at the start are literal, as in `[!#.]`, `[a-]` and `[]a]`
- `[\b]` is a backspace
- Negated classes, and `\D`, `\W` and `\S`, give printable ASCII characters where the class allows any

### Escape Sequences

- `\d` - digit \[0-9\]
- `\w` - word character \[a-zA-Z0-9\_\]
- `\s` - whitespace
- `\D` - non-digit
- `\W` - non-word character
- `\S` - non-whitespace
- `\b`, `\B` - word boundary and non-boundary
- `\A`, `\z`, `\Z` - start and end of string, `\Z` also allowing a final newline
- `\x41`, `\x{263A}` - characters given in hexadecimal
- `\t`, `\n`, `\r` - tab, newline, carriage return
- `\p{L}`, `\p{Lu}`, `\p{Ll}`, `\p{N}`, `\p{Nd}`, `\p{P}`, `\p{S}`, `\p{Z}` - Unicode properties

### Quantifiers

- `{n}` - exactly n times
- `{n,m}` - between n and m times
- `{n,}` - n or more times (n to n+4 times)
- `{,n}` - up to n times, from Perl 5.34
- `+` - one or more (1-5 times)
- `*` - zero or more (0-5 times)
- `?` - zero or one
- `++`, `*+`, `?+`, `{n,m}+` - possessive quantifiers
- `+?`, `*?`, `??`, `{n,m}?` - lazy quantifiers

From Perl 5.34 there may be blanks within the braces, as in `a{ 1, 3 }`.
Braces which do not form a quantifier, such as those in `a{x}`, are literal characters,
but a pattern or group cannot start with one.

### Grouping and Alternation

- `(...)` - capturing group
- `(?:...)` - non-capturing group
- `(?>...)` - atomic group
- `(?i)` - inline case insensitivity. Strings use the case written in the pattern
- `|` - alternation (e.g., `cat|dog|bird`)
- `(?<name>...)` - named capturing group
- `\1` to `\9` - backreferences, with groups numbered by their opening parenthesis
- `\g1`, `\g{1}` - backreferences, and `\g{-1}` counting back from the latest group
- `\k<name>`, `\k{name}`, `\k'name'`, `\g{name}` - named backreference
- Backreferences may be quantified, as in `(a)\1{2}`
- Groups and alternations may be nested, an alternative may be empty, and alternation need not be within a group
- Each repetition of a group is generated separately, so `(a|b){3}` can give `aba`.
A backreference to the group is to its last repetition
- Groups in alternatives which are not chosen still take a number
- A group which is left out captures nothing, so with `(a)?\1` it is always included

### Lookaheads and Lookbehinds

`(?=...)`, `(?!...)`, `(?<=...)` and `(?<!...)` are supported.
Generated strings match the regex, and are accepted by `validate()`.

- A lookahead at the end of the pattern, or a lookbehind at the start,
needs text next to the match, so that text is included in the string.
`qr/\d{3}(?=[A-Z])/` generates strings such as `123A`,
and `qr/(?<=\$)\d{2}/` strings such as `$42`.
`validate()` requires that text too.
- Elsewhere they restrict what may be generated,
as in `qr/^(?!000)\d{3}$/`.
Candidates are generated until one matches.

### Other

- `.` - any character (printable ASCII, excluding the space)
- Literal characters
- `^` and `$` anchors (stripped during parsing)
- The `/x` and `/xx` modifiers, and the inline `(?x)` flag: the whitespace and comments which they allow generate nothing

## Limitations

- Lookarounds are satisfied by trial and error,
so a very restrictive one, such as `qr/(?=XYZ)\w{3}/`,
can fail after the maximum number of attempts.
Only a lookbehind at the very start, or a lookahead at the very end,
of the pattern or of one of its top level alternatives adds text;
one inside a group does not.
- Negated Unicode properties (`\P{...}`) are not supported
- Other Unicode properties are treated as ASCII letters
- Some complex nested patterns may not work correctly with smart parsing

## Examples

```perl
    # Email-like pattern
    my $gen = Data::Random::String::Matches->new(qr/[a-z]+@[a-z]+\.com/);

    # API key pattern
    my $gen = Data::Random::String::Matches->new(qr/^AIza[0-9A-Za-z_-]{35}$/);

    # Phone number
    my $gen = Data::Random::String::Matches->new(qr/\d{3}-\d{3}-\d{4}/);

    # Repeated pattern
    my $gen = Data::Random::String::Matches->new(qr/(\w{4})-\1/);
```

## Methods

### New($Regex, $Length)

Creates a new generator. `$regex` can be a compiled regex (qr//) or a string.
`$length` is optional and defaults to 10 (used for fallback generation).

#### Messages

- `Regex pattern is required` - `$regex` is not defined
- A string which is not a valid regex dies with the error from Perl

#### Api Specification

##### Input

```perl
# Compatible with Params::Validate::Strict:
{
    regex  => { type => [ 'string', 'regex' ] },
    length => { type => 'integer', min => 1, optional => 1, default => 10 },
}
# Passed by position: new($regex, $length)
```

##### Output

```perl
# Compatible with Return::Set:
{ type => 'object', isa => 'Data::Random::String::Matches' }
```

### Generate($Max\_Attempts)

Generates a random string matching the regex. First tries smart parsing, then
falls back to brute force if needed. Tries up to `$max_attempts` times
(default 1000) before croaking.

#### Messages

- `Failed to generate matching string after %d attempts. Pattern: %s`
- With the environment variable `DEBUG_REGEX_GEN` set, a warning says why smart parsing failed

#### Api Specification

##### Input

```perl
# Compatible with Params::Validate::Strict:
{
    max_attempts => { type => 'integer', min => 1, optional => 1, default => 1000 },
}
# Passed by position
```

##### Output

```perl
# Compatible with Return::Set:
{ type => 'string' }
```

### Generate\_Smart()

Parses the regex and builds a matching string directly. Faster and more reliable
than brute force, but may not handle all edge cases.
A backreference to a group which was left out, as can happen with `(a)?\1`,
cannot match, so it tries again, up to 1000 times.
For patterns with lookarounds, word boundaries, `\A`, `\z`, `\Z`, atomic groups
or inline flags it tries up to 1000 times to build a string which
matches, then croaks.

#### Messages

- `Failed to generate matching string after 1000 attempts. Pattern: %s`
- `Backreference %s used before group defined`, or `Named backreference %s used before group defined`
- `Unmatched [`, `Unmatched (` or `Quantifier '%s' without preceding element` - the pattern could not be parsed

#### Api Specification

##### Input

```
# Compatible with Params::Validate::Strict:
{}
```

##### Output

```perl
# Compatible with Return::Set:
{ type => 'string' }
```

### Generate\_Many($Count, $Unique)

Generates multiple random strings matching the regex.

```perl
my @strings = $gen->generate_many(10);           # 10 strings (may have duplicates)
my @strings = $gen->generate_many(10, 1);        # 10 unique strings
my @strings = $gen->generate_many(10, 'unique'); # 10 unique strings

# Generate until you have 1000 unique codes
my $gen = Data::Random::String::Matches->new(qr/[A-Z]{3}\d{4}/);
my @codes = $gen->generate_many(1000, 'unique');
```

Parameters:

- `$count` - Number of strings to generate (required, must be positive)
- `$unique` - If true, ensures all generated strings are unique. May return fewer
than `$count` strings if uniqueness cannot be achieved within reasonable attempts.
Accepts any true value (1, 'unique', etc.)
Up to 100 strings are generated for each one requested.

Returns: List of generated strings, in the order they were generated.
In scalar context, the number of strings.

#### Messages

- `Count must be a positive integer`
- `Only generated %d unique strings out of %d requested` - a warning; the strings which were found are returned
- Any message from `generate()`

#### Api Specification

##### Input

```perl
# Compatible with Params::Validate::Strict:
{
    count  => { type => 'integer', min => 1 },
    unique => { type => 'boolean', optional => 1, default => 0 },
}
# Passed by position
```

##### Output

```perl
# Compatible with Return::Set:
# Returned as a list: this describes [ $gen->generate_many($count) ]
{ type => 'arrayref', element_type => 'string' }
```

### Get\_Seed()

Gets the random seed for reproducible generation.
Returns `undef` if `set_seed()` has not been called on this object.

#### Api Specification

##### Input

```
# Compatible with Params::Validate::Strict:
{}
```

##### Output

```perl
# Compatible with Return::Set:
{ type => 'integer', optional => 1 }  # undef until set_seed() is called
```

### Set\_Seed($Seed)

Sets the random seed for reproducible generation,
and returns the object so that calls can be chained.
Any defined value, including 0, may be used.
This calls `srand()`, so it also affects every other use of Perl's random number generator.

```perl
my $str = $gen->set_seed(42)->generate();
```

#### Messages

- `Seed must be defined`

#### Api Specification

##### Input

```perl
# Compatible with Params::Validate::Strict:
{
    seed => { type => 'integer' },
}
# set_seed($seed), set_seed(seed => $seed) or set_seed({ seed => $seed })
```

##### Output

```perl
# Compatible with Return::Set:
{ type => 'object', isa => 'Data::Random::String::Matches' }  # for chaining
```

### Suggest\_Simpler\_Pattern()

Analyzes patterns and suggests improvements.

```perl
my $suggestion = $gen->suggest_simpler_pattern();

if ($suggestion) {
  print "Reason: $suggestion->{reason}\n";
  print "Better pattern: $suggestion->{pattern}\n" if $suggestion->{pattern};
  print "Tips:\n";
  print "  - $_\n" for @{$suggestion->{tips}};
}
```

Returns `undef` if there is nothing to suggest, otherwise a reference to a hash with these keys:

- `reason` - why the suggestion is made
- `tips` - a reference to an array of advice
- `pattern` - a replacement pattern, or `undef` where none can be offered

Only the first of these which applies is reported:

- A very complex pattern. No replacement
- Backreferences. No replacement
- A range `{n,m}` more than 10 wide. The replacement uses the midpoint
- More than 10 alternatives. No replacement
- A group of three single letters, such as `(a|b|c)`. The replacement is a class, `[abc]`
- Lookarounds. Those at the edges are replaced by ordinary groups; for others there is no replacement
- `\p{L}`. The replacement is `[A-Za-z]`
- A run of 20 or more literal letters. No replacement

Apart from the one for lookarounds, a replacement does not generate the same set of strings.

#### Api Specification

##### Input

```
# Compatible with Params::Validate::Strict:
{}
```

##### Output

```perl
# Compatible with Return::Set:
# undef if there is nothing to suggest, otherwise
{
    type   => 'hashref',
    schema => {
        pattern => { type => 'string', optional => 1 },  # may be undef
        reason  => { type => 'string' },
        tips    => { type => 'arrayref' },
    },
}
```

### Validate($String)

Checks if a string matches the pattern without generating.
The whole string must match: a trailing newline is not ignored.
Returns 1 if it does, otherwise 0.

```
if ($gen->validate('1234')) {
  print "Valid!\n";
}
```

#### Messages

- `String must be defined`

#### Api Specification

##### Input

```perl
# Compatible with Params::Validate::Strict:
{
    string => { type => 'string' },
}
# validate($string), validate(string => $string) or validate({ string => $string })
```

##### Output

```perl
# Compatible with Return::Set:
{ type => 'boolean' }
```

### Pattern\_Info()

Returns detailed information about the pattern.

```perl
my $info = $gen->pattern_info();
print "Complexity: $info->{complexity}\n";
print "Min length: $info->{min_length}\n";
print "Has Unicode: ", $info->{features}{has_unicode} ? "Yes" : "No", "\n";
```

The result is a reference to a hash with these keys:

- `pattern` - the pattern, as a string
- `min_length`, `max_length` - the shortest and longest strings which would be generated
- `estimated_length` - midway between the two, rounded down
- `features` - a reference to a hash of the flags below, each 1 or 0
- `complexity` - `simple`, `moderate`, `complex` or `very_complex`, from the length of the pattern and its features

The flags are:

- `has_alternation`
- `has_backreferences`
- `has_lookahead`, `has_lookbehind`
- `has_named_groups`
- `has_possessive` - possessive quantifiers
- `has_unicode` - Unicode properties, `\p`

The lengths are estimates.
They follow the repetition counts used for generation, so `a+` is taken to be 1 to 5 characters.
The result is calculated once for each object, and the same reference is returned each time.

#### Api Specification

##### Input

```
# Compatible with Params::Validate::Strict:
{}
```

##### Output

```perl
# Compatible with Return::Set:
{
    type   => 'hashref',
    schema => {
        pattern          => { type => 'string' },
        min_length       => { type => 'integer' },
        max_length       => { type => 'integer' },
        estimated_length => { type => 'integer' },
        features         => { type => 'hashref' },  # has_* booleans
        complexity       => { type => 'string', memberof => [ 'simple', 'moderate', 'complex', 'very_complex' ] },
    },
}
```

### Create\_Random\_String

For consistency with [Data::Random::String](https://metacpan.org/pod/Data%3A%3ARandom%3A%3AString).

```perl
print Data::Random::String::Matches->create_random_string(length => 3, regex => '\d{3}'), "\n";
```

This is a class method which creates a generator and calls `generate()` once.
It takes named parameters, or a reference to a hash of them:

- `regex` - the pattern, required
- `length` - as for `new()`, optional

#### Messages

- `Regex pattern is required`
- Any message from `new()` or `generate()`

#### Api Specification

##### Input

```perl
# Compatible with Params::Validate::Strict:
{
    regex  => { type => [ 'string', 'regex' ] },
    length => { type => 'integer', min => 1, optional => 1, default => 10 },
}
# Class method: named parameters or a hash reference
```

##### Output

```perl
# Compatible with Return::Set:
{ type => 'string' }
```

## Author

Nigel Horne, `<njh at nigelhorne.com>`

## See Also

- [Test Dashboard](https://nigelhorne.github.io/Data-Random-String-Matches/coverage/)
- [String::Random](https://metacpan.org/pod/String%3A%3ARandom)
- [Regexp::Genex](https://metacpan.org/pod/Regexp%3A%3AGenex)

## Licence and Copyright

Copyright 2025-2026 Nigel Horne.

Usage is subject to the GPL2 licence terms.
If you use it,
please let me know.
