user9847788
user9847788

Reputation: 2433

RegEx pattern not asserting true

I am trying to compare the below string to a regular expression pattern in my java project:

2018-11-12 12:02:04.075

I've passed the above string into an online regular expression generator to generate the following pattern:

((?:2|1)\d{3}(?:-|\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))

Below is my ASSERT statement, but when I run this test I get an assertion error:

assertTrue(rs.getString(this.columnName).matches("((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))"));

What changes do I need to make to get this test to pass? Is it a problem with my regex?

Upvotes: 2

Views: 238

Answers (3)

Aeiman Bakeer
Aeiman Bakeer

Reputation: 490

Try this

[12]\\d{3}-(0[1-9]|1[12])-(0[1-9]|1[0-9]|2[0-9]|3[01])\\s([01][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9]\\.\\d{3}

Upvotes: 0

vignesh
vignesh

Reputation: 16

Try using one of the following regexes:

((?:2|1)\d{3}(?:-|\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9].(?:[0-9][0-9][0-9])))

or

((?:2|1)\d{3}(?:-|\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]).(\d{3}))

or

(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{3})

Upvotes: 0

Evgeni Enchev
Evgeni Enchev

Reputation: 552

You are missing the miliseconds part. Try this:

((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9])\\.\\d{3})

Upvotes: 2

Related Questions