Xbase++ Requires Chilkat v11.1.0+
Xbase++
Regular Expression with Multiple Matches and Named Capture Groups
See more Regular Expressions Examples
Demonstrates regular expressions with named capture groups and multiple matches.Chilkat Xbase++ Downloads
LOCAL nSuccess
LOCAL oSb
LOCAL nCrlf
LOCAL cPattern
LOCAL oJson
LOCAL nTimeoutMs
LOCAL nNumMatches
LOCAL nIdx_first
LOCAL nIdx_last
LOCAL i
LOCAL nMatchCount
nSuccess := 0
oSb := CreateObject("Chilkat.StringBuilder")
nCrlf := 1
oSb:AppendLine("Name: John Smith", nCrlf)
oSb:AppendLine("Name: Jack Johnson", nCrlf)
oSb:AppendLine("Name: Mary Adams", nCrlf)
? oSb:GetAsString()
// We have the following string:
// Name: John Smith
// Name: Jack Johnson
// Name: Mary Adams
cPattern := "Name:\s+(?<first>\w+)\s+(?<last>\w+)"
oJson := CreateObject("Chilkat.JsonObject")
oJson:EmitCompact := 0
nTimeoutMs := 2000
nNumMatches := oSb:RegexMatch(cPattern, oJson, nTimeoutMs)
IF (nNumMatches < 0)
// Probably an error in the regular expression.
// Suggestion: Use AI to help create and/or diagnose regular expressions.
? oSb:LastErrorText
oSb:destroy()
oJson:destroy()
RETURN
ENDIF
// Examine the matches:
? oJson: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": "Name: John Smith",
// "idx": 0,
// "len": 16
// },
// {
// "cap": "John",
// "idx": 6,
// "len": 4
// },
// {
// "cap": "Smith",
// "idx": 11,
// "len": 5
// }
// ]
// },
// {
// "group": [
// {
// "cap": "Name: Jack Johnson",
// "idx": 18,
// "len": 18
// },
// {
// "cap": "Jack",
// "idx": 24,
// "len": 4
// },
// {
// "cap": "Johnson",
// "idx": 29,
// "len": 7
// }
// ]
// },
// {
// "group": [
// {
// "cap": "Name: Mary Adams",
// "idx": 38,
// "len": 16
// },
// {
// "cap": "Mary",
// "idx": 44,
// "len": 4
// },
// {
// "cap": "Adams",
// "idx": 49,
// "len": 5
// }
// ]
// }
// ]
// }
// The capture group index is obtained by looking up the name in the JSON result.
// For example:
nIdx_first := oJson:IntOf("named.first")
nIdx_last := oJson:IntOf("named.last")
i := 0
nMatchCount := oJson:SizeOfArray("match")
DO WHILE i < nMatchCount
? "Match " + Str(i + 1) + ":"
oJson:I := i
oJson:J := nIdx_first
? "first: " + oJson:StringOf("match[i].group[j].cap")
oJson:J := nIdx_last
? "first: " + oJson:StringOf("match[i].group[j].cap")
? ""
i := i + 1
ENDDO
// Output is:
// Match 1:
// first: John
// first: Smith
//
// Match 2:
// first: Jack
// first: Johnson
//
// Match 3:
// first: Mary
// first: Adams
oSb:destroy()
oJson:destroy()