Can I convert a string with space using totitle? - tcl

The Tcl documentation is clear on how to use string totitle:
Returns a value equal to string except that the first character in
string is converted to its Unicode title case variant (or upper case
if there is no title case variant) and the rest of the string is
converted to lower case.
Is there a workaround or method that will convert a string with spaces (the first letter of each word would be upper case)?
For example in Python:
intro : str = "hello world".title()
print(intro) # Will print Hello World, notice the capital H and W.

In Tcl 8.7, the absolutely most canonical way of doing this is to use regsub with the -command option to apply string totitle to the substrings you want to alter:
set str "hello world"
# Very simple RE: (greedy) sequence of word characters
set tcstr [regsub -all -command {\w+} $str {string totitle}]
puts $tcstr
In earlier versions of Tcl, you don't have that option so you need a two stage transformation:
set tcstr [subst [regsub -all {\w+} $str {[string totitle &]}]]
The problem with this is that it will below up if the input string has certain Tcl metacharacters in it; it is possible to fix this, but it's horrible to do; I added the -command option to regsub precisely because I was fed up of having to do a multi-stage substitute just to make a string I could feed through subst. Here's the safe version (the input stage could also be done with string map):
set tcstr [subst [regsub -all {\w+} [regsub -all {[][$\\]} $str {\\&}] {[string totitle &]}]]
It gets really complicated (well, at least quite non-obvious) when you want to actually do the replacement on substrings that have been transformed. Which is why it is now possible to circumvent all that mess with regsub -command that is careful with word boundaries when doing the replacement command running (because the Tcl C API is actually good at that).

Donal gave you an answer but there is a package that allows you to do what you want textutil::string from Tcllib
package require textutil::string
puts [::textutil::string::capEachWord "hello world"]
> Hello World

Related

How to search for 0,a1[4],* where * is a wildcard in a list of 0,a2,4 0,a1[4],3 0,a1[4],5 .... in tcl

I tried lsearch -all $list_ 0,a1[4],*
a1[4] is stored in a variable
SO basically need
set var "a1[4]"
lsearch -all $list_ 0,$var,*
By default lsearch uses glob patterns (as described by the documentation for string match — it's the exact same matching engine being used). That's good because it means that * is a wildcard, but awkward because it means that [ is also special (it starts a character set match). You need some simple escaping, and to keep that sane you should put your whole pattern in {braces} so we don't need to fight with Tcl over what the meanings of bracket and backslash are:
lsearch -all $list_ {0,a1\[4\],*}
You don't need braces; you could write this instead:
lsearch -all $list_ 0,a1\\\[4\\\],*
But that's ugly! And difficult to maintain (trust me on that). So use braces, OK?
In the case where you're pulling the subpattern from a variable, things get more complicated. The fix is to use string map (or regsub) to condition the pattern piece.
# Split into three lines for clarity; qvar = “quoted var”
set ADD_BACKSLASHES {[ {\[} ] {\]}}
set qvar [string map $ADD_BACKSLASHES $var]
lsearch -all $list_ 0,$qvar,*

Tcl - passing curly braces into a variable within a regsub command

I need to pass a regular expression as a variable within a regsub command. I want to eliminate the brackets from cap variable, but I am unable to pass the curly braces within the match variable.
set cap {[equality choice control]}
set match {\[}
regsub -all $match $cap "" cap
puts $cap
The reason for doing this is that I am building a proc and I need to pass the regex as an argument.
Square brackets are special in regular expressions as well as Tcl. To match a literal bracket you need to escape it in the regular expression and it needs separate escaping in Tcl.
% set match {[}
[
% regsub -all $match $cap ""
couldn't compile regular expression pattern: brackets [] not balanced
% set match {\[}
\[
% regsub -all $match $cap ""
equality choice control]
You could also use quotes but ensure you deal with the Tcl escaping requirements. ie: set match "\\\["
Note: for a simple substitution you may find string map easier to use:
set cap [string map [list "\[" ""] $cap]
would achieve the same effect.

How to trim two words from right of a string

I want to remove two words from right of a string.
For example:
set str "sachin is the pride of india"
I need to remove india and of from right and there should be no space after that.
I have tried using string trimright.
The string trimright command is exactly the wrong tool for this; it treats its trim argument as a set of characters to remove, not a literal. The simplest way of doing this is with lreplace, provided the string doesn't contain list metacharacters and you don't care about the number of spaces.
set shortened [lreplace $str end-1 end]
If you need to do it reliably, regular expressions are the tool of choice.
set shortened [regsub {\s*\S+\s+\S+\s*$} $str ""]
Use regsub for this. Please.

Is there any Tcl function to add escape character automatically?

Is there any Tcl function to add escape character to a string automatically?
For example, I have a regular expression
"[xy]"
After I call the function, I get
"\[xy]"
After being called again, I get
"\\\[xy]"
I remember there's such function with some script language, but I cannot recall which language it is.
The usual way of adding such escape characters as are “necessary” is to use list (% is my Tcl prompt):
% set s {[xy]}
[xy]
% set s [list $s]
{[xy]}
% set s [list $s]
{{[xy]}}
The list command prefers to leave alone if it can, wrap with braces if it can get away with it, and resorts to backslashing otherwise (because backslashes are really unreadable).
If you really need backslashes, string map or regsub will do what you need. For example:
set s [regsub -all {\W} $s {\\&}]

Grep the word inside double quote

How can I extract a word inside a double quote inside a file?
e.g.
variable "xxx"
Reading a text file into Tcl is just this:
set fd [open $filename]
set data [read $fd] ;# Now $data is the entire contents of the file
close $fd
To get the first quoted string (under some assumptions, notably a lack backslashed double quote characters inside the double quotes), use this:
if {[regexp {"([^""]*)"} $data -> substring]} {
# We found one, it's now in $substring
}
(Doubling up the quote in the brackets is totally unnecessary — only one is needed — but it does mean that the highlighter does the right thing here.)
The simplest method of finding all the quoted strings is this:
foreach {- substring} [regexp -inline -all {"([^""]*)"} $data] {
# One of the substrings is $substring at this point
}
Notice that I'm using the same regular expression in each case. Indeed, it's actually good practice to factor such REs (especially if repeatedly used) into a variable of their own so that you can “name” them.
Combining all that stuff above:
set FindQuoted {"([^""]*)"}
set fd [open $filename]
foreach {- substring} [regexp -inline -all $FindQuoted [read $fd]] {
puts "I have found $substring for you"
}
close $fd
Internal Matching
If you're just looking for a regular expression, then you can use TCL's capture groups. For example:
set string {variable "xxx"}
regexp {"(.*)"} $string match group1
puts $group1
This will return xxx, discarding the quotes.
External Matching
If you want to match data in a file without having to handling reading the file into TCL directly, you can do that too. For example:
set match [exec sed {s/^variable "\(...\)"/\1/} /tmp/foo]
This will call sed to find just the parts of the match you want, and assign them to a TCL variable for further process. In this example, the match variable is set to xxx as above, but is operating on an external file rather than a stored string.
When you just want to find with grep all words in quotes in a file and do something with the words, you do something like this (in a shell):
grep -o '"[^"]*"' | while read word
do
# do something with $word
echo extracted: $word
done