Bruce
Bruce

Reputation: 81

How to specify matching a literal asterisk in a json schema pattern

I want to specify a pattern in a json schema that would require an asterisk at the beginning of a string that can only contain 2 characters such as:

*A

I have tried the following pattern but it does not work:

"code": {
  "type": "string",
  "pattern": "^[*A-Z]{2}$"
}

The above pattern allows: *A and AA which is not what I want.

I am using the ajv json schema validator.

Upvotes: 1

Views: 1032

Answers (2)

The fourth bird
The fourth bird

Reputation: 163237

Your pattern ^[*A-Z]{2}$ allows 2 times either an asterix, or a character in the range A-Z

If you want to allow 2 characters, and the first has to be an asterix:

^\*[A-Z]$

Regex demo

Upvotes: 3

Major
Major

Reputation: 562

The regex [*A-Z]{2} matches either *, or A-Z. Asterisks are a bit odd, so you need to make it its own group. Try this out: ^[*][A-Z]{2}$

Edit: I'm assuming you mean it needs an asterisk followed by 2 characters, like *BC or *AE. If you mean it must start with an asterisk followed by exactly one character, just remove the {2}.

Upvotes: 3

Related Questions