简体   繁体   中英

Pattern matching using regular expressions

I have these two strings:

  1. "2013-01-28 12:10:01.680000".

  2. "2013-01-28 12:10:01".

I want a regular expression which will return true for all strings which start with: xxxx-xx-xx xx:xx:xx , when x is a number, no matter what the suffix is (value from the point and after).

Now I use:

final String ACCEPTED_FORMAT = "\\\\d{4}-\\\\d{2}-\\\\d{2} \\\\d{2}:\\\\d{2}:\\\\d{2}.\\\\d{6}";

But I don't want to check the value after the point in the strings.

This should do the job I think:

final String ACCEPTED_FORMAT = 
        "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(\\.\\d{6})?";

It makes the '.' and the 6 digits after it optional.


However, this is NOT a good way to validate dates, because it allow all sort of nonsense, include non-existent months, days beyond the end of the month and so on. There are proper date parsers ... and you should use one, if you want to validate the date properly.

(And I find it hard to imagine why you wouldn't want to validate the dates properly. What is the utility in allowing the user to enter nonsense like "2011-02-32 99:99:99" ?)

I think your regex must be

\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(\\.\\d{6})?

EDIT:- @Stephen C- The Dot character also must be escaped. (Dot would match any character)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM