nmvictor
nmvictor

Reputation: 1129

Regex to match 17 Uppercase characters

Which Regex, in java, would be more suitable to match a string 17 characters long, all uppercased and does not include the letters I (i), O (o), or Q (q).

I have tried the following but it still matches I,O and Q inclusive and even more or less than 17

^[A-Z]+

How do i improve this?

Upvotes: 3

Views: 1745

Answers (3)

Nagappan
Nagappan

Reputation: 356

Upper case string can be compared using quantifiers with elimination in the sequence. To limit the number of characters if we use matches method in Matcher class, it will check for the exact sequence below.

    String upperCaseString = new String("ABCDEABCDEABCDEAE");
    System.out.println("value is " + Pattern.compile("([A-Z&&[^IOQ]]){17}").matcher(upperCaseString).matches());

Upvotes: 0

npinti
npinti

Reputation: 52185

There are 3 problems with your approach:

  1. You are matching any upper case English character. To solve this, you will need to replace [A-Z] with [A-HJ-NPR-Z]. This should match from A to H, from J to N, the letter P and from R to Z.

  2. The second problem is that you are matching one or more (due to the +). To match exactly 17 characters, the + will need to become {17}.

  3. Steps 1 and 2 will simply match any string which contains 17 upper case letters within the range stipulated. To make sure that the string does not contain anything else, add ^ at the beginning and $ at the end of your expression. This will make sure that the string is not made out of anything else.

As a result, your expression should look as follows: ^[A-HJ-NPR-Z]{17}$. An example of the regular expression is available here.

Upvotes: 6

vks
vks

Reputation: 67978

^(?!.*(?:[IOQ]))[A-Z]{17}$

Just add a lookahead.See demo.

https://regex101.com/r/uF4oY4/24

Upvotes: 5

Related Questions