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

Regular Expression Replace Capture Groups

See more Regular Expressions Examples

Demonstrates replacing capture groups for a regular expression.

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

Chilkat CkPython Downloads

CkPython
import sys
import chilkat

success = False

subject = "John Anders, +_+_+ Mary Robins $$$$"
pattern = "(?<first>\\w+)\\s+(?<last>\\w+)"

sb = chilkat.CkStringBuilder()
sb.Append(subject)

json = chilkat.CkJsonObject()
json.put_EmitCompact(False)

timeoutMs = 2000
numMatches = sb.RegexMatch(pattern,json,timeoutMs)
if (numMatches < 0):
    #  Probably an error in the regular expression.
    #  Suggestion: Use AI to help create and/or diagnose regular expressions.
    print(sb.lastErrorText())
    sys.exit()

#  Examine the matches:
print(json.emit())

#  There are 2 matches:

#  {
#    "named": {
#      "first": 1,
#      "last": 2
#    },
#    "match": [
#      {
#        "group": [
#          {
#            "cap": "John Anders",
#            "idx": 0,
#            "len": 11
#          },
#          {
#            "cap": "John",
#            "idx": 0,
#            "len": 4
#          },
#          {
#            "cap": "Anders",
#            "idx": 5,
#            "len": 6
#          }
#        ]
#      },
#      {
#        "group": [
#          {
#            "cap": "Mary Robins",
#            "idx": 19,
#            "len": 11
#          },
#          {
#            "cap": "Mary",
#            "idx": 19,
#            "len": 4
#          },
#          {
#            "cap": "Robins",
#            "idx": 24,
#            "len": 6
#          }
#        ]
#      }
#    ]
#  }

#  To replace capture groups, write code to examine each capture group within
#  each match, and provide a replacement string.
#  Then call RegexReplace.

#  For example, let's capitalize the first names, and add append "on" to the last name.
#  After doing replacements, we should get:  JOHN Anderson, +_+_+ MARY Robinson $$$$

firstNameIdx = json.IntOf("named.first")
lastNameIdx = json.IntOf("named.last")

sbTemp = chilkat.CkStringBuilder()

i = 0
numMatches = json.SizeOfArray("match")
while i < numMatches :

    json.put_I(i)

    #  The replacement string for the first name will be all uppercase.
    json.put_J(firstNameIdx)
    sbTemp.Clear()
    json.StringOfSb("match[i].group[j].cap",sbTemp)
    sbTemp.ToUppercase()
    json.UpdateSb("match[i].group[j].rep",sbTemp)

    #  Append "on" to the last name.
    json.put_J(lastNameIdx)
    sbTemp.Clear()
    json.StringOfSb("match[i].group[j].cap",sbTemp)
    sbTemp.Append("on")
    json.UpdateSb("match[i].group[j].rep",sbTemp)

    i = i + 1

#  The JSON now has replacement strings:
print(json.emit())

#  {
#    "named": {
#      "first": 1,
#      "last": 2
#    },
#    "match": [
#      {
#        "group": [
#          {
#            "cap": "John Anders",
#            "idx": 0,
#            "len": 11
#          },
#          {
#            "cap": "John",
#            "idx": 0,
#            "len": 4,
#            "rep": "JOHN"
#          },
#          {
#            "cap": "Anders",
#            "idx": 5,
#            "len": 6,
#            "rep": "Anderson"
#          }
#        ]
#      },
#      {
#        "group": [
#          {
#            "cap": "Mary Robins",
#            "idx": 19,
#            "len": 11
#          },
#          {
#            "cap": "Mary",
#            "idx": 19,
#            "len": 4,
#            "rep": "MARY"
#          },
#          {
#            "cap": "Robins",
#            "idx": 24,
#            "len": 6,
#            "rep": "Robinson"
#          }
#        ]
#      }
#    ]
#  }

#  Call RegexReplace to update the StringBuilder with the replacements.
success = sb.RegexReplace(json)
if (success == False):
    print(sb.lastErrorText())
    sys.exit()

print("Result after doing replacements:")
print(sb.getAsString())

#  Result after doing replacements:
#  JOHN Anderson, +_+_+ MARY Robinson $$$$