Search code examples
regexdelphipcre

Delphi TRegEx.IsMatch: How to match an empty string?


How to match for an empty string using Delphi (10.3) TRegEx.IsMatch?

The following cases return false where I would expect to return true:

fDoesMatch := TRegEx.IsMatch('', '^$');
fDoesMatch := TRegEx.IsMatch('', '^.{0}$');
fDoesMatch := TRegEx.IsMatch('', '\A\z');

As I've seen in the docs https://docwiki.embarcadero.com/Libraries/Sydney/en/System.RegularExpressions.TRegEx Delphi uses C library "PCRE" under the hood to do the regex.

Trying that regex patterns at https://regex101.com/ matches so i wonder why it does not work with Delphi


Solution

  • TRegEx by default does not match empty strings, because it is created with undocumented roNotEmpty option.

    You must explicitly exclude roNotEmpty option to enable empty string matches:

    fDoesMatch := TRegEx.IsMatch('', '^$', []);
    

    The decision to use [roNotEmpty] as the default was made to maintain backwards compatibility with older Delphi versions. See A Subtle Delphi TRegEx Change.