![]() |
Chilkat HOME Android™ AutoIt C C# C++ Chilkat2-Python CkPython Classic ASP DataFlex Delphi DLL Go Java Node.js Objective-C PHP Extension Perl PowerBuilder PowerShell PureBasic Ruby SQL Server Swift Tcl Unicode C Unicode C++ VB.NET VBScript Visual Basic 6.0 Visual FoxPro Xojo Plugin
(Visual FoxPro) Regular Expression with Multiple Matches and Named Capture GroupsSee more Regular Expressions ExamplesDemonstrates regular expressions with named capture groups and multiple matches.Note: This example requires Chilkat v11.1.0 or greater.
LOCAL lnSuccess LOCAL loSb LOCAL lnCrlf LOCAL lcPattern LOCAL loJson LOCAL lnTimeoutMs LOCAL lnNumMatches LOCAL lnIdx_first LOCAL lnIdx_last LOCAL i LOCAL lnMatchCount lnSuccess = 0 loSb = CreateObject('Chilkat.StringBuilder') lnCrlf = 1 loSb.AppendLine("Name: John Smith",lnCrlf) loSb.AppendLine("Name: Jack Johnson",lnCrlf) loSb.AppendLine("Name: Mary Adams",lnCrlf) ? loSb.GetAsString() * We have the following string: * Name: John Smith * Name: Jack Johnson * Name: Mary Adams lcPattern = "Name:\s+(?<first>\w+)\s+(?<last>\w+)" loJson = CreateObject('Chilkat.JsonObject') loJson.EmitCompact = 0 lnTimeoutMs = 2000 lnNumMatches = loSb.RegexMatch(lcPattern,loJson,lnTimeoutMs) IF (lnNumMatches < 0) THEN * Probably an error in the regular expression. * Suggestion: Use AI to help create and/or diagnose regular expressions. ? loSb.LastErrorText RELEASE loSb RELEASE loJson CANCEL ENDIF * Examine the matches: ? loJson.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: lnIdx_first = loJson.IntOf("named.first") lnIdx_last = loJson.IntOf("named.last") i = 0 lnMatchCount = loJson.SizeOfArray("match") DO WHILE i < lnMatchCount ? "Match " + STR(i + 1) + ":" loJson.I = i loJson.J = lnIdx_first ? "first: " + loJson.StringOf("match[i].group[j].cap") loJson.J = lnIdx_last ? "first: " + loJson.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 RELEASE loSb RELEASE loJson |
© 2000-2025 Chilkat Software, Inc. All Rights Reserved.