1

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

It's not needed to put * in brackets. A back-escape is sufficient to escape any special character (and then another backslash for the JSON encoding).
I tried all of the suggested comments and I ended up using this"pattern": "^\*[A-Z]$" . This pattern also works: "pattern": "^[*][A-Z]$" . For some reason it does not show the second backslash when I save my edit. Thank you all very much !
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.