user1580348
user1580348

Reputation: 6053

Check whether a string is a valid URL in Delphi?

In a Delphi 10.4.2 win-32 VCL Application in Windows 10, I try to check whether a string is a valid URL.

Of course, I have examined the answers at: https://stackoverflow.com/search?q=delphi+check+valid+url
and: What is the best regular expression to check if a string is a valid URL?

A few of those regular expressions are so long (e.g. 5500 characters) that they cannot be pasted as a string constant in the Delphi code editor. Others simply don't work in this context (Delphi).

This is what I tried, using TRegEx and ShLwApi:

function TformMain.IsValidURL(const AUrl: string): Boolean;
const
  RE = '/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/';
begin
  Result := False;
  if AUrl = '' then EXIT;

  // Does not work: 'https://www.google.c' is detected as valid:
  //Result := TRegEx.IsMatch(AUrl, '\A\b(?:(?:https?|ftps?|file)://|www\.|ftp|com\.)[-A-Z0-9+&@#/%=~_|$?!:,.]*[A-Z0-9+&@#/%=~_|$]\z', [roIgnoreCase]);

  // Does not work: almost everything starting with 'https:' is valid:
  //Result := Boolean(ShLwApi.PathIsURL(PChar(AUrl)));

  // Does not work with 'https://www.google.com':
  //Result := TRegEx.IsMatch(AUrl, RE, [roIgnoreCase]);
end;

The solution should be only string-based (not connecting to the Internet).

I suspect that there may have to be a very simple solution.

Upvotes: 0

Views: 1694

Answers (1)

Uwe Raabe
Uwe Raabe

Reputation: 47758

Delphi 10.4.2 offers a record TURI in System.Net.URLClient.pas. Calling the constructor Create with your URL will raise an ENetURIException for an invalid URL.

Upvotes: 2

Related Questions