humkins
humkins

Reputation: 10705

limit total number of characters in regex

The string can be a number or a set of numbers, or two groups of numbers separated with "-", but total count of all characters mustn't be more than 6.

Example of valid strings

5
55-33
4444-1
1-4444
666666

Example of invalid strings

-3
6666-
5555-6666

My regex

/^\d+(-?\d+)?$/

But this regex interprets 5555-6666 as a valid string, though its length is more than 6 characters.

I tried following

/^(\d+(-?\d+)?){1,6}$/

but, than I recognized that it interpret enclosed charset as one group, which it expects from 1 to 6.

So how to control total number of chars just with a regexp and requirements described above?

Upvotes: 0

Views: 2864

Answers (3)

Code Maniac
Code Maniac

Reputation: 37775

Method 1 :-

Easiest thing you can do it is testing the length before regex (i will prefer using this method which checks length and then use regex)

str.length < 7 && /^\d+(-?\d+)?$/.test(str)

Method 2 :-

You can use positive lookahead

^(?=.{0,6}$)\d+(-?\d+)?$

enter image description here

Regex Demo

Upvotes: 3

blhsing
blhsing

Reputation: 107124

You can use a positive lookahead pattern to ensure that there can be a maximum of 6 characters:

^(?=.{1,6}$)\d+(?:-\d+)?$

Demo: https://regex101.com/r/kAxuZp/1

Or you can a negative lookahead pattern to ensure that the string does not start with a dash, and another negative lookahead pattern to ensure that the string does not contain two dashes:

^(?!-)(?!.*-.*-)[\d-]{0,5}\d$

Demo: https://regex101.com/r/kAxuZp/3

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

One option would be to use your current regex pattern and also check the length of the input with dash removed:

var input = "4444-1";
if (/^\d+(-?\d+)?$/.test(input) && input.replace("-", "").length <= 6) {
    console.log("MATCH");
}
else {
    console.log("NO MATCH");
}

Note that checking the length of the input is only really meaningful after the dash has been removed, because it is only then that we can assert the total number of actual digits.

Upvotes: 0

Related Questions