How do I get the Named Groups of a Regex in Delphi?

Viewed 2713

I'm trying to use regex on Delphi to regex a HTML and get some data.

My objective is create a query string with the follow sintax:

?namedGroup1=valueNamedGroup1&namedGroup2=valueNamedGroup2

I have n Array of regex:

array[0] = '<div (id="(?<id>[a-zA-Z0-9]+)"|name="(?<name>[a-zA-Z0-9]+))"';

My html:

<h1>bla bla bla</h1> <div id="home">

If I apply this regex using the built in regex in PHP it will return an associative array

RegArray[0] = '<div id="home">'
RegArray['id'] = 'home'

if I do a foreach I easily get the list of the named groups and I can create my querystring:

?id=home

The thing is that I don't know if the regex will match the named group ID or Name and I need to know that.

Delphi only return a simple array

RegArray[0] = '<div id="home">'
RegArray[1] = 'home'  // ID or NAME?

So, how do I get the named Group and the named Group Value?

here it is my code:

var RegEx: TRegEx;
begin
 RegEx := TRegEx.Create(array[0], [roIgnoreCase,roMultiline]);
 Match := RegEx.Match(html);
 if (Match.Success) then
 begin
   //get the group here.
 end;

I also tried this class: http://www.regular-expressions.info/delphi.html

But no success

3 Answers

TRegEx (from System.RegularExpressions) is a wrapper around TPerlRegEx (from System.RegularExpressionsCore), which is a wrapper around the open source PCRE library.

PCRE of course supports retrieving the names for groups, but both wrappers don't.

Possible solutions:

  • Ask Embarcadero to fix it
  • Access PCRE directly (System.RegularExpressionsAPI)
  • Use one of the two wrappers, but for retrieving the names, hack into their private members to get access to the PCRE memory (pcre_fullinfo(TPerlRegEx.FPattern, ...))
  • Use a better wrapper, i.e. JclPCRE from the open source JEDI Code Library (JCL): Name1:= TJclRegEx.CaptureNames[1];
Related