Deepak Deepak - 1 month ago 16
Javascript Question

Regex for Number format Validation

Help with regex to match for this Number pattern .. I need accept the input only in below formats.For implementing this validation logic i need regex.
I tried using following

/(^(([0-9]{5,6}[,])+[0-9]{5,6})$)|(^(([0-9]{1,5}\*[,])+[0-9]{1,5}\*)$)|(^(([0-9]{5,6}[,])+[0-9]{1,5}\*)$)|(^(([0-9]{1,5}\*[,])+[0-9]{1,5})$)/


But it is not matching all scenarios.

Following are the possible inputs


  1. 1123*,2133*,123*,1*

  2. 213433,123453,123*

  3. 123333,123623,678123,12323,

  4. 1123*,123445,166788,123333,..........



Conditions - Number can have length 5 or 6. Inputs must be separated by comma. If input has * (Wildcard search) then max length cannot be greater than 5. ex 123123(Not allowed)*

Answer

I'm not sure I completely understand the requirements of the RegExp matching pattern, but here's a preliminary approach.

  • As I understand you, Numbers [to be matched] can have length 5 or 6 and that the matching pattern should be able to capture any amount of numbers that fit this description. For this part, I will assume there are no asterisk characters (*) contained in a number sequence.

Let's assume we have a variable input that is assigned as a value the string 213433,123453,123*. Then...

input.match(/\d{5,6}(?!\*)/g);

should capture parts of the input variable as so described. I noticed you were using character sets in your attempt (i.e., the [0-9] part); the \d term accomplishes the same thing.The (?!\*) portion is used to check that the 5- or 6-digit sequence is not followed by an asterisk character. Note: You have to escape the asterisk.

  • In the event an input does possess an asterisk character, the matched portion can be no longer than 5 characters. (I hope I'm understanding the prompt correctly)! For this, the following RegExp pattern worked for the (admittedly inexhaustive) two tests I ran. Note: This pattern retains (i.e., matches/captures) the asterisk character as well as the number sequence.

We can assume that the input variable here is assigned to the string 1123*,2133*,123*,1* for purposes of testing out the next RegExp match pattern.

input.match(/(\d+\*){1,5}/g);

If I'm not mistaken, the two match patterns can be conditionally combined using a simple OR (|) operator.

input.match(/\d{5,6}(?!\*)|(\d+\*){1,5}/g);

Hopefully, that helps a bit. As a final test, let's assign the input variable to the string 1123*,2133*,123*,1*,123333,123623,678123,12323 (I concatenated example inputs 1. and 3. that you provided for this). Then, running the statement directly above returns the array:

["1123*", "2133*", "123*", "1*", "123333", "123623", "678123", "12323"]

If you wanted to retrieve the matches WITHOUT any wildcard characters (*), you could simply modify the expression as follows:

a.match(/\d{5,6}(?!\*)|(\d+\*){1,5}/g).map(val => val.replace('*', ''));

to get...

["1123, "2133", "123", "1", "123333", "123623", "678123", "12323"]