2

I want to create a control on the iban with the following characteristics :
- minimum 14 characters
- maximum 34 characters
- the first 2 characters are always two letters (country identifier)
- the 3rd and 4th characters always two digits (control keys (from 02 to 98)
I am trying to develop a simple REGEX in Java with pattern like that:

@Pattern(
    regexp = "[a-zA-Z]{2}([2-9]|[1-8][0-9]|9[0-8]){2}[a-zA-Z0-9]{4}[0-9]{6}([a-zA-Z0-9]?){0,20}", 
    message = "Le format de l'iban est invalide"
)

The problem for the 3rd and 4th character is that the system does not accept these conditions (10,20,30,40,50,60,70,80,90) although these numbers are included in the interval [ 02-98]

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
BNJ
  • 108
  • 1
  • 8
  • There is a utility for it mentioned in [this answer](https://stackoverflow.com/a/27499109/3832970) – Wiktor Stribiżew Nov 12 '19 at 09:25
  • Sorry but it not worked for me – BNJ Nov 12 '19 at 09:41
  • 1
    And what did you try? It can't fail to work. The patterns are accurate there. – Wiktor Stribiżew Nov 12 '19 at 09:44
  • I am trying to execute this regex code @Pattern(regexp = "[a-zA-Z]{2}([2-9]|[1-8][0-9]|9[0-8]){2}[a-zA-Z0-9]{4}[0-9]{6}([a-zA-Z0-9]?){0,20}", message = "Le format de l'iban est invalide") from this site http://gamon.webfactional.com/regexnumericrangegenerator/ the problem that 99 and 01 (the 3rd and 4th character) is accepted – BNJ Nov 12 '19 at 09:53
  • But you did not account for the fact that a single digit number should be preceded by a `0`. Otherwise, the number will be matched with the `[a-zA-Z0-9]{4}` pattern. Please update the question with this pattern since this is now making more sense. – Wiktor Stribiżew Nov 12 '19 at 10:04
  • Try `^[a-zA-Z]{2}(?:0[2-9]|[1-8][0-9]|9[0-8])[a-zA-Z0-9]{4}[0-9]{6}[a-zA-Z0-9]{0,20}$`, see the [demo](https://regex101.com/r/dvyQ4v/1). – Wiktor Stribiżew Nov 12 '19 at 10:05

1 Answers1

1

You may use

^[a-zA-Z]{2}(?:0[2-9]|[1-8][0-9]|9[0-8])[a-zA-Z0-9]{4}[0-9]{6}[a-zA-Z0-9]{0,20}$

The ([2-9]|[1-8][0-9]|9[0-8]){2} part is replaced with (?:0[2-9]|[1-8][0-9]|9[0-8]). Your ([2-9]|[1-8][0-9]|9[0-8]){2} matches two occurrences of a digit between 2 and 9, or two occurrences of numbers between 10 and 98. So, you need to add 0 to the first alternative and remove the {2} quantifier.

See the regex demo

Details

  • ^ - start of string
  • [a-zA-Z]{2} - two ASCII letters
  • (?:0[2-9]|[1-8][0-9]|9[0-8]) - a number between 02 to 98
  • [a-zA-Z0-9]{4} - four ASCII alphanumeric chars
  • [0-9]{6} - six digits
  • [a-zA-Z0-9]{0,20} - 0 to 20 ASCII alphanumeric chars
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563