VFDevelopper
VFDevelopper

Reputation: 33

How to make a regex for decimal that has a defined length (comma included)

I am looking for a 15 characters length regex with a decimal. In the swift documentation, the regex would look like this : 3!a15d where 3!a means [a-zA-Z]{3} and 15d means a decimal of 15 characters length with a comma.

I tried the regex below :

([A-Z]{3}[0-9]{1,14}[,][0-9]{1})|([A-Z]{3}[0-9]{1,13}[,][0-9]{1,2})|([0-9]{1,12}[,][0-9]{1,3})|([0-9]{1,11}[,][0-9]{1,4})|([0-9]{1,10}[,][0-9]{1,5})|([0-9]{1,9}[,][0-9]{1,6})|([0-9]{1,8}[,][0-9]{1,7})|([0-9]{1,7}[,][0-9]{1,8})|([0-9]{1,6}[,][0-9]{1,9})|([0-9]{1,5}[,][0-9]{1,10})|([0-9]{1,4}[,][0-9]{1,11})|([0-9]{1,3}[,][0-9]{1,12})|([0-9]{1,2}[,][0-9]{1,13})|[0-9]{1}[,][0-9]{1,14}

But it didn't work. Do you have any tips to help me?

Upvotes: 2

Views: 103

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You can use

^[a-zA-Z]{3}(?=[^,]*,[^,]*$)\d(?:,?\d){14}$

See the regex demo.

Details:

  • ^ - start of string
  • [a-zA-Z]{3} - three ASCII letters
  • (?=[^,]*,[^,]*$) - only one obligatory comma must be present further in the string
  • \d - a digit
  • (?:,?\d){14} - fourteen repetitions of an optional comma and a digit
  • $ - end of string.

Sample usage in Java to validate a string:

Boolean isValid = text.matches("[a-zA-Z]{3}(?=[^,]*,[^,]*$)\\d(?:,?\\d){14}");

Upvotes: 2

Related Questions