Reputation: 2433
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
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
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
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