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

Time:01-23

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

CodePudding user response:

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.

  • Related