Sample code for 30+ languages & platforms
Tcl

Regular Expression Replace Full Matches

See more Regular Expressions Examples

Demonstrates replacing the full matches of a regular expression.

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

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

set success 0

set subject "John Anders, +_+_+ Mary Robins $$$$"
set pattern "\\w+\\s+\\w+"

set sb [new_CkStringBuilder]

CkStringBuilder_Append $sb $subject

set json [new_CkJsonObject]

CkJsonObject_put_EmitCompact $json 0

set timeoutMs 2000
set numMatches [CkStringBuilder_RegexMatch $sb $pattern $json $timeoutMs]
if {$numMatches < 0} then {
    # Probably an error in the regular expression.
    # Suggestion: Use AI to help create and/or diagnose regular expressions.
    puts [CkStringBuilder_lastErrorText $sb]
    delete_CkStringBuilder $sb
    delete_CkJsonObject $json
    exit
}

# Examine the matches:
puts [CkJsonObject_emit $json]

# {
#   "match": [
#     {
#       "group": [
#         {
#           "cap": "John Anders",
#           "idx": 0,
#           "len": 11
#         }
#       ]
#     },
#     {
#       "group": [
#         {
#           "cap": "Mary Robins",
#           "idx": 19,
#           "len": 11
#         }
#       ]
#     }
#   ]
# }

set sbTemp [new_CkStringBuilder]

set i 0
set numMatches [CkJsonObject_SizeOfArray $json "match"]
while {$i < $numMatches} {

    CkJsonObject_put_I $json $i

    # The full match is always in group 0.
    CkStringBuilder_Clear $sbTemp
    CkJsonObject_StringOfSb $json "match[i].group[0].cap" $sbTemp

    # Indicate that we wish to replace the full match with it's value converted to uppercase.
    CkStringBuilder_ToUppercase $sbTemp
    CkJsonObject_UpdateSb $json "match[i].group[0].rep" $sbTemp

    set i [expr $i + 1]
}

# The JSON now has replacement strings:
puts [CkJsonObject_emit $json]

# {
#   "match": [
#     {
#       "group": [
#         {
#           "cap": "John Anders",
#           "idx": 0,
#           "len": 11,
#           "rep": "JOHN ANDERS"
#         }
#       ]
#     },
#     {
#       "group": [
#         {
#           "cap": "Mary Robins",
#           "idx": 19,
#           "len": 11,
#           "rep": "MARY ROBINS"
#         }
#       ]
#     }
#   ]
# }

# Call RegexReplace to update the StringBuilder with the replacements.
set success [CkStringBuilder_RegexReplace $sb $json]
if {$success == 0} then {
    puts [CkStringBuilder_lastErrorText $sb]
    delete_CkStringBuilder $sb
    delete_CkJsonObject $json
    delete_CkStringBuilder $sbTemp
    exit
}

puts "Result after doing replacements:"
puts [CkStringBuilder_getAsString $sb]

# Result after doing replacements:
# JOHN ANDERS, +_+_+ MARY ROBINS $$$$

delete_CkStringBuilder $sb
delete_CkJsonObject $json
delete_CkStringBuilder $sbTemp