![]() |
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
(Tcl) Regular Expression Replace Full MatchesSee more Regular Expressions ExamplesDemonstrates replacing the full matches of a regular expression.Note: Chilkat uses Note: This example requires Chilkat v11.1.0 or greater.
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 |
© 2000-2025 Chilkat Software, Inc. All Rights Reserved.