Jessica
Jessica

Reputation: 3769

How can I check for 2 characters with a regular expression?

I used the following to check for two digits.

"^\d{2}$"

But how can I change this so I check for two digits or uppercase A-Z?

Upvotes: 2

Views: 2435

Answers (3)

kendaleiv
kendaleiv

Reputation: 5813

^[A-Z|\d]{2}$

matches AA and 11 but not A, 1, AAA, or 111 (the A-Z specifies uppercase only)

Edit: This will also match 1A and C3 (see comment by Jason), if this is not what you want do not use this answer.

Upvotes: 2

Jason
Jason

Reputation: 3960

Use this, will match the items in bold only:

^\d{2}|[A-Z]{2}$
  • 25
  • ab
  • AB
  • 2A
  • A3
  • -23
  • -AB

If you also want to match against negatives, you can try this one:

^-?\d{2}|[^-][A-Z]{2}$

And will match these

  • 25
  • ab
  • AB
  • 2A
  • A3
  • -23
  • -AB

Upvotes: 1

Ani
Ani

Reputation: 113442

2 consecutive digits or 1 uppercase character:

\d{2}|[A-Z]

2 consecutive digits or 2 consecutive uppercase characters:

\d{2}|[A-Z]{2}

2 consecutive digit / uppercase characters:

[\dA-Z]{2}

Upvotes: 3

Related Questions