Reputation: 801
I have following code to match a string with format 1ab11ab111
where 1= Any Number 0 to 9
and a or b = Any character a to z or A to Z
var str = "1ab11ab111";
var patt1 = /[0-9]+[a-z]+[a-z]+[0-9]+[0-9]+[a-z]+[a-z]+[0-9]+[0-9]+[0-9]/i;
So is there any simpler method/ code for the same string match?
Upvotes: 0
Views: 59
Reputation: 149040
Well [0-9]
can be simplified to \d
. If each one of those character classes is meant to match exactly one character (rather than one or more as it does now), you can similar character classes together with a single {…}
quantifier, like this:
var patt1 = /\d[a-z]{2}\d{2}[a-z]{2}\d{3}/;
This will match and string consisting of a single digit, followed by two lower case Latin letters, followed by two digits, followed by two lower case Latin letters, followed by three digits.
But it can be simplified even more by grouping certain elements together, like this:
var patt1 = /(\d[a-z]\d){2}\d{2}/;
This will match all of a single digit, followed by two lower case Latin letters, followed by a single digit, captured into group 1, which must appear twice, followed by two digits.
Also note, both these will match any sequence of characters which matches this pattern anywhere in the string—e.g. 'foo1ab11ab111bar'
would be a valid match. If this is a problem, use a start (^
) and end ($
) anchor to prevent any characters appearing before or after the matched substring, like this:
var patt1 = /^(\d[a-z]\d){2}\d{2}$/;
Upvotes: 3
Reputation: 133423
You can use /[0-9][a-z]{2}[0-9]{2}[a-z]{2}[0-9]{3}/i
You can use \d
in place of [0-9]
. Thus the pattern will be using \d
/\d[a-z]{2}\d{2}[a-z]{2}\d{3}/i
You test this at http://regex101.com/r/fS9cB6
Upvotes: 1
Reputation: 32921
This regular expression you provided would match any string containing lower case letters and numbers.
I think you actually want:
/^\d[a-z]{2}\d{2}[a-z]{2}\d{3}$/i
Here's how I tested:
/^\d[a-z]{2}\d{2}[a-z]{2}\d{3}$/i.test('1ab11ab111'); // true
/^\d[a-z]{2}\d{2}[a-z]{2}\d{3}$/i.test('1ab11Ab111'); // true
/^\d[a-z]{2}\d{2}[a-z]{2}\d{3}$/i.test('1ab11ab11'); // false
Upvotes: 2