0

I need to recognize if a string has the proper mysql DB time stamp format in javascript. I wrote this regexp:

var regex = /([0..9]{4})-([0..9]{2})-([0..9]{2}) ([0..9]{2}):([0..9]{2}):([0..9]{2})/;

However when used with the string

var s = "2014-09-08 08:02:17";
if (regex.test){
   console.log("OK");
}

It doesn't work. Can anyone tell me what I did wrong?

3
  • 1
    replace .. with -.. Commented Apr 29, 2016 at 12:33
  • Thank you. Please post it as answer so I can mark it right. Worst part about it is that I looked it up and did not see the difference. Commented Apr 29, 2016 at 12:35
  • @aarelovich try this link to test your regex Commented Apr 29, 2016 at 12:36

3 Answers 3

2

The regex for this date format is : (\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})

Here a JsFiddle : https://jsfiddle.net/2vh23Lmt/

    var string = "2014-09-08 08:02:17";
    var re = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/g;
    if (re.test(string)) {
        console.log("Valid");
    } else {
        console.log("Invalid");
    }

Sign up to request clarification or add additional context in comments.

1 Comment

([\d]{4}-[\d]{2}-[\d]{2} (?:[\d]{2}:){2}[\d]{2}) will complete it faster, as it takes less steps (7 according to my regex tester). It all depends on whether the op is doing 1 or many. here
1

There's 2 errors in your approach:

  • a) incorrect character class [0..9](should be [0-9]);
  • b) tested string is not specified in regex.test function call

 var regex = /[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/g;
 var s = "2014-09-08 08:02:17";
 if (regex.test(s)){
    console.log("OK");
 }

Comments

0

Add anchors and replace .. with -. Because - inside a character class (not at the first or last) should act like a range quantifier.

var regex = /^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/;

And anchors, yes it's must. Otherwise your regex should match this 54632014-09-08 08:02:173563 . Anchors will do an exact match, you may replace anchors with \b if you don't want to do an exact match.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.