I am trying to match DateTime input using the Pattern and Matcher class of Apex but wasn't able to achieve it.

I've created a regex for matching the Datetime input as follows and it matches the datetime input '2021-01-01 12:34' in regex validate site as follows.


However it throws No Match found in Apex,

A simple Utility class as follows,

public with sharing class DateUtility {
    public static final Pattern REGEX_DATETIME = Pattern.compile('\\d{2,4}-\\d{1,2}-\\d{1,2}(\\s+)\\d{1,2}');

    public static Datetime deserializeDateTime(String bodyDateTimeString) {
        Matcher strMatch = REGEX_DATETIME.matcher(bodyDateTimeString);
        System.debug('2222 ' + strMatch.matches());
        System.debug('ZZZZ ' + strMatch.groupCount());
        //Some Logics

        Datetime convertedDT;
        return convertedDT;

In Anonymous,

DateTime response = Ppm_DateUtility.deserializeDateTime('2021-01-01 12:34');
System.debug('The response is ' + response);

What I have missed over here?

1 Answer 1


Of course it doesn't match; you are checking for 'XXXX-XX-XX XX', but the string is in the form 'XXXX-XX-XX XX:XX'. The matches function matches the entire string, not just a substring. Use find if you want to have less than a full string match, or fix your regex as '\\d{2,4}-\\d{1,2}-\\d{1,2}(\\s+)\\d{1,2}:\\d{1,2}'.

  • I have to match a substring. As you explained find is the correct function in my scenario. Learnt a lot in the unknown context. Thanks. Jan 20, 2022 at 3:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .