5er
5er

Reputation: 2695

regular expression in Java (Spring configuration) with 2 specific characters in begining

I need regular expression which will start with 2 specific letters and will be 28 characters long. The regular expression is needed, as this is in conjunction with Spring configuration, which will only take a regular expression.

I've been trying to do with this, it's not working (^[AK][28]*)

Upvotes: 0

Views: 773

Answers (3)

Laurent B
Laurent B

Reputation: 2220

If you need to count the number of repetitions use the {min, max} syntax. Omiting both the comma and max tells the regex parser to look for exactly minrepetitions.

For example :

.{1,3} will match for any character (shown by the dot) sequence between 1 and 3 characters long.

[AK]{2} will match for exactly 2 characters that are either A or K : AK, AA, KA or KK.

Additionnaly, your regex uses [AK]. This means that it will match against one of the characters given, i.e. A or K.

If you need to match for the specific "AK" sequence then you need to get rid of the '[' ']' tokens.

Therefore you regex could be AK.{28} meaning it will match for AK followed by exactly 28 characters.

Upvotes: 0

dot_Sp0T
dot_Sp0T

Reputation: 399

Regex is nothing specific to Java, nor is it that difficult if you have a look at any tutorial (and there's plenty!).

To answer your question:

AK[a-zA-Z]{26}

The above regex should solve your issue regarding a 28 character String with the first two letters being AK.

Elaboration:

  • AK[a-zA-Z]{26}
    > Characters written as such, without any special characters will be matched as is (that means they must be where they were written, in exactly that fashion)
  • AK[a-zA-Z]{26}
    > By using square brackets you can define a set of characters, signs, etc. to be matched against a part of the regex (1 by default) - you can write down all the possible characters/signs or make use of groups (e.g. a-z, /d for digits, and so forth)
  • AK[a-zA-Z]{26}
    > for each set of characters/signs you can define a repetition count, this defines how often the set can/must be applied. E.g. {26} means it must match 26 times. Other possibilities are {2, 26} meaning it must match at least 2 times but at most 26 times, or for example use an operator like *, + or ? which denote that the set can be matched 0 or more times, at least once or 0 or 1 time

In case you need it matching a whole line you would likely want to add ^ and $ at the beginning and end respectively, to tell the regex parser that it has to match a whole line/String and not just a part:

^AK[a-zA-Z]{26}$

Upvotes: 0

assylias
assylias

Reputation: 328598

If you mean that the string should be like "AKxxxxxxxx" (28 characters in total), then you can use:

^AK.{26}$ //using 26 since AK already count for 2 characters

Upvotes: 3

Related Questions