Diar
Diar

Reputation: 133

Regex for yyyy-mm-dd

So this is my input (valid date-time): 2019-03-14 18:00:00

I want to match 2019-03-14

This is my regex: \d{4}-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])*

But it gives me 3 matches. 2019-03-14, 03, 4

What should I change to just match: 2019-03-14 ?

Upvotes: 0

Views: 547

Answers (2)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92427

Try

let d= "2019-03-14 18:00:00".split(' ')[0];

let r= "2019-03-14 18:00:00".match(/[^ ]*/)[0];

console.log('split: ', d);
console.log('regexp:', r);

Upvotes: 2

user2226755
user2226755

Reputation: 13167

enter image description here

You can use a non-capturing group (the parentheses will not remember the match) with ?:

\d{4}-(?:0?[1-9]|1[012])-(?:0?[1-9]|[12][0-9]|3[01])*

var regex = /\d{4}-(?:0?[1-9]|1[012])-(?:0?[1-9]|[12][0-9]|3[01])*/;

console.log("2019-03-14 18:00:00".match(regex));

Upvotes: 2

Related Questions