javascript - Confusing with Regular Expressions repeaing parts -


i confused regular expressions repeating parts curly braces. consider following example:

var datetime = /\d{1,2}\/\d{1,2}\/\d{4} \d{1,2}:\d{2}/; console.log(datetime.test("30/1/2003 8:45")); // true 

now if change 30 300000 , 45 455555, i'll true again! other parts between outer numbers ok , result expected.

can me find problem?

thanks.

you're not matching beginning , end of string (^ , $) it's finding match anywhere in string still happens, , giving true.

300000/1/2003 8:455555     dd/m/yyyy h:mm 

you want

/^\d{1,2}\/\d{1,2}\/\d{4} \d{1,2}:\d{2}$/; 

or more exact;

/^(?:0?[1-9]|[12]\d|3[01])\/(?:0?[1-9]|1[0-2])\/\d{4} (?:0?\d|1\d|2[0-3]):[0-5]\d$/; 
  • (?:pattern) non capture group
  • pattern? n in pattern optional
  • [1-9] character class; number ranging 1 9
  • pattern1|pattern2 either pattern1 or pattern2
  • [12] character class; either 1 or 2
  • \d same [0-9]
  • pattern{4} n in pattern happens 4 times

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -