Sample code for 30+ languages & platforms
PowerBuilder Requires Chilkat v11.1.0+

Regular Expression with Named Capture Groups

See more Regular Expressions Examples

Demonstrates regular expressions with named capture groups.

See the sample code below.

Note: Chilkat uses PCRE2. See PCRE2 Regular Expressions
Also see: PCRE2 Performance

In PCRE2, named capture groups allow you to assign a name to a capturing group, making it easier to reference by name instead of number.

Syntax

(?<name>pattern)

or

(?'name'pattern)

Example

(?<first>\w+)\s+(?<last>\w+)

Applied to:

"John Smith"

Produces:

  • first: John
  • last: Smith

Chilkat PowerBuilder Downloads

PowerBuilder
integer li_rc
integer li_Success
string ls_Subject
string ls_Pattern
oleobject loo_Sb
oleobject loo_Json
integer li_TimeoutMs
integer li_NumMatches

li_Success = 0

ls_Subject = "John Smith"
ls_Pattern = "(?<first>\w+)\s+(?<last>\w+)"

loo_Sb = create oleobject
li_rc = loo_Sb.ConnectToNewObject("Chilkat.StringBuilder")
if li_rc < 0 then
    destroy loo_Sb
    MessageBox("Error","Connecting to COM object failed")
    return
end if
loo_Sb.Append(ls_Subject)

loo_Json = create oleobject
li_rc = loo_Json.ConnectToNewObject("Chilkat.JsonObject")

loo_Json.EmitCompact = 0

li_TimeoutMs = 2000
li_NumMatches = loo_Sb.RegexMatch(ls_Pattern,loo_Json,li_TimeoutMs)
if li_NumMatches < 0 then
    //  Probably an error in the regular expression.
    //  Suggestion: Use AI to help create and/or diagnose regular expressions.
    Write-Debug loo_Sb.LastErrorText
    destroy loo_Sb
    destroy loo_Json
    return
end if

//  Examine the matches:
Write-Debug loo_Json.Emit()

//  Here is the JSON showing the matches.
//  Important:  Capture group 0 always contains the entire match — that is, the portion of the input string that matches the full regular expression.

//  {
//    "named": {
//      "first": 1,
//      "last": 2
//    },
//    "match": [
//      {
//        "group": [
//          {
//            "cap": "John Smith",
//            "idx": 0,
//            "len": 10
//          },
//          {
//            "cap": "John",
//            "idx": 0,
//            "len": 4
//          },
//          {
//            "cap": "Smith",
//            "idx": 5,
//            "len": 5
//          }
//        ]
//      }
//    ]
//  }

//  The capture group index is obtained by looking up the name in the JSON result.
//  For example:

loo_Json.I = loo_Json.IntOf("named.first")
Write-Debug "first: " + loo_Json.StringOf("match[0].group[i].cap")

loo_Json.I = loo_Json.IntOf("named.last")
Write-Debug "last: " + loo_Json.StringOf("match[0].group[i].cap")

//  Output is: 

//  first: John
//  last: Smith


destroy loo_Sb
destroy loo_Json