Swagger fails to generate a valid example for complex regex patterns.
Q&A (please complete the following information)
- OS: Windows 11
- Browser: Brave, Firefox
- Version: latest?
- Method of installation: yarn]
- Swagger-UI version: 4.6.2
- Swagger/OpenAPI version: Swagger 2.0
Content & configuration
Example Swagger/OpenAPI definition:
{
type: 'string',
pattern: '^[A-Za-z0-9]+\.(png|jpg|jpeg){1}$',
minLength: 39,
maxLength: 54,
description: 'A randomly generated unique id with the file extension',
}
Describe the bug you're encountering
Swagger does not generate a valid example for complex regex patterns. It generates a random string that does not match the provided pattern.
Initially this was my regex ^(?=.{39,54}$)([A-Za-z0-9]+\.(png|jpg|jpeg){1})$, it was completely ignoring the length check (besides not matching the extension) then I read somewhere that the first check it's not supported, so I began to use minLength and maxLength removing the need for the first check. Now they are matching the length specified in the properties, but still not matching the regex pattern ^[A-Za-z0-9]+\.(png|jpg|jpeg){1}$.
Actually not even this website https://onlinestringtools.com/generate-string-from-regex can generate a proper one. My guess is the specification used by Swagger (ECMA-262 or some customized version) might have properties/limitations I'm not aware of. The regex patterns I'm producing work just fine and pass my own tests locally and on websites such as https://regexr.com/ and https://www.regexpal.com/.
I'd like to hear your take on the issue and if there's any workaround for it, besides strictly defining the example.
To reproduce...
Steps to reproduce the behavior:
- Create a field for a string that requires a complex regex pattern:
type: 'string',
pattern: '^[A-Za-z0-9]+\.(png|jpg|jpeg){1}$',
minLength: 39,
maxLength: 54,
description: 'A randomly generated unique id with the file extension',
- Make sure everything else is fine.
- Run the server and go see the generated documentation
- See the error
Expected behavior
I expected swagger to be able to generate a proper string that matches the given regex.
Screenshots
Sometimes the extension doesn't appear at all, and you can try to test using the generated string, it fails.

+1
Same for me with the regex: ^[a-zA-Z0-9](-*[a-zA-Z0-9]|\.?[a-zA-Z0-9])*$
It almost always generates examples that end with a -, although that is not valid.
The same for ^[^.]+$.
Use example to provide static value.