javascript - Restricting Character length in Regular expression -


i using following regular expression without restricting character length

var test =  /^(a-z|a-z|0-9)*[^$%^&*;:,<>?()\""\']*$/ //works fine 

in above when trying restrict characters length 15 below, throws error.

var test =  /^(a-z|a-z|0-9)*[^$%^&*;:,<>?()\""\']*${1,15}/    //**uncaught syntaxerror: invalid regular expression** 

please me make above regex work characters limit 15.

you cannot apply quantifiers anchors. instead, to restrict length of input string, use lookahead anchored @ beginning:

^(?=.{1,15}$)[a-za-z0-9]*[^$%^&*;:,<>?()\"']*$   ^^^^^^^^^^^ 

also, assume wanted match 0 or more letters or digits (a-z|a-z|0-9)*. should [a-za-z0-9]* (i.e. use character class here).

why not use limiting quantifier, {1,15}, @ end?

quantifiers applied subpattern left, group or character class, or literal symbol. thus, ^[a-za-z0-9]*[^$%^&*;:,<>?()\"']{1,15}$ restrict length of second character class [^$%^&*;:,<>?()\"'] 1 15 characters. ^(?:[a-za-z0-9]*[^$%^&*;:,<>?()\"']*){1,15}$ "restrict" sequence of 2 subpatterns of unlimited length (as * (and +, too) can match unlimited number of characters) 1 15 times, , still not restrict length of whole input string.

how lookahead restriction work?

the (?=.{1,15}$) positive lookahead appears right after ^ start-of-string anchor. zero-width assertion returns true or false after checking if subpattern matches subsequent characters. so, lookahead tries match 1 15 (due limiting quantifier {1,15}) characters newline right @ end of string (due $ anchor). if remove $ anchor lookahead, lookahead require string contain 1 15 characters, total string length can any.

if input string can contain newline sequence, should use [\s\s] portable any-character regex construct (it work in js , other common regex flavors):

^(?=[\s\s]{1,15}$)[a-za-z0-9]*[^$%^&*;:,<>?()\"']*$  ^^^^^^^^^^^^^^^^^ 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -