## 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]`

### Escape Sequences

- `\d` - digit \[0-9\]
- `\w` - word character \[a-zA-Z0-9\_\]
- `\s` - whitespace
- `\D` - non-digit
- `\W` - non-word character
- `\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
- `+` - one or more (1-5 times)
- `*` - zero or more (0-5 times)
- `?` - zero or one
- `++`, `*+`, `?+`, `{n,m}+` - possessive quantifiers

### Grouping and Alternation

- `(...)` - capturing group
- `(?:...)` - non-capturing group
- `|` - alternation (e.g., `cat|dog|bird`)
- `(?<name`...)> - named capturing group
- `\1` to `\9` - backreferences, with groups numbered by their opening parenthesis
- `\k<name`> - named backreference

### 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)
- Literal characters
- `^` and `$` anchors (stripped during parsing)

## 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).

### 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.

### 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.
For patterns with lookarounds it tries up to 1000 times to build a string which
matches, then croaks.

### 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.)

Returns: List of generated strings

Dies: If count is not a positive integer

Warns: If unable to generate the requested number of unique strings

### Get\_Seed()

Gets the random seed for reproducible generation

### Set\_Seed($Seed)

Sets the random seed for reproducible generation

### 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}};
}
```

### Validate($String)

Checks if a string matches the pattern without generating.

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

### 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";
```

`pattern_info` analyzes a regular expression to produce a structured summary of its characteristics,
including estimated string lengths, detected features, and an overall complexity rating.
It first calls `_estimate_length` to heuristically compute the minimum and maximum possible lengths of strings matching the pattern by scanning for literals,
character classes, and quantifiers.
It then detects the presence of advanced regex constructions such as alternation, lookahead or lookbehind assertions, named groups, and Unicode properties, storing them in a feature hash.
Finally, it calculates a rough "complexity" classification based on pattern length and detected features-returning a hash reference that describes the regex's structure, estimated lengths, and complexity level.

### 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";
```

## 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.
