regsub not working properly with string tolower

108 Views Asked by At

Im trying to make the first letter of that pattern lowercase.

 set filestr {"FooBar": "HelloWorld",}
 regsub -all {([A-Z])([A-Za-z]+":)} $filestr "[string tolower "\\1"]\\2" newStr

However the string tolower is not doing anything

2

There are 2 best solutions below

1
On BEST ANSWER

This is a 2 step process in Tcl:

set tmp [regsub -all {([A-Z])([A-Za-z]+":)} $filestr {[string tolower "\1"]\2}]
"[string tolower "F"]ooBar": "HelloWorld",

Here we have added the syntax for lower casing the letter. Note how I have used non-interpolating braces instead of double quotes for the replacement part. Now we apply the subst command to actually apply the command:

set newStr [subst $tmp]
"fooBar": "HelloWorld",
0
On

In Tcl 8.7, you can do this in a single step with the new command substitution capability of regsub:

set filestr {"FooBar": "HelloWorld",}

# The backslash in the RE is just to make the highlighting here not suck
regsub -all -command {([A-Z])([A-Za-z]+\":)} $filestr {apply {{- a b} {
    string cat [string tolower $a] $b
}}} newStr

If you'd wanted to convert the entire word to lower case, you'd have been able to use this simpler version:

regsub -all -command {[A-Z][A-Za-z]+(?=\":)} $filestr {string tolower} newStr

But it doesn't work here because you need to match the whole word and pass it all through the transformation command; using lookahead constraints for the remains of the word allows those remains to be matched on the internal search for a match.