List Info

Thread: Regsub Problem




Regsub Problem
country flaguser name
United States
2007-10-01 09:50:13
Hello, I have a need to remove delimiters from various
strings and
capitalize the first char following a delimiter match and
then recombine
everything into one string.  My first attempt was to use
split to break
apart the string using a list of delimiters and save the
parts into a
list.  Then run through the list of parts using totitle and
recombine
everything into a new string.  All worked as planned, see
attempt 1.  

Attempt 1;

set delimiters {%|*|$||!|#|&|^|_|-|,|.|;|:| }
set test [list {thaddeus Cooper} 
               {%idiotic_Field*name} 
               {hey#hey#Hey,hello_world} 
              
{this#is_a_test_of_the-emergency-broadcast-system}]

foreach item $test {
   set str ""
   set mylist [split $item, $delimiters]
   foreach thing $mylist {
      set s [string totitle $thing]
      append str $s
   }
   puts $str
}

Result 1:
D:Projects>tclsh pascalcase.tcl
ThaddeusCooper
IdioticFieldName
HeyHeyHeyHelloWorld
ThisIsATestOfTheEmergencyBroadcastSystem


Wanting to improve upon this method I thought about using
regsub to do
all the dirty work.  Attempt 2 shows my effort but does not
work
properly.  I have 2 issues:

Issue 1: The variable $delimiters does not work properly
within the
regsub--just not matches, that is why I had to implicitly
hard-code the
pattern.  Why??  I tried multiple escaping the chars and
still not
working.

Issue 2: The substitute part, [string toupper ] does
nothing.  Why??

Attempt 2:

set delimiters {%|*|$||!|#|&|^|_|-|,|.|;|:| }
set test [list {thaddeus Cooper} 
               {%idiotic_Field*name} 
               {hey#hey#Hey,hello_world} 
              
{this#is_a_test_of_the-emergency-broadcast-system}]

foreach item $test {
   regsub -all -- {(%|*|$||!|#|&|^|_|-|,|.|;|:| )(w)} $item
[string toupper ] item1
   puts $item1
}

Result 2:
D:Projects>tclsh pascalcase.tcl
thaddeusCooper
idioticFieldname
heyheyHeyhelloworld
thisisatestoftheemergencybroadcastsystem


Now to make this more interesting I did the same thing in
Perl and it
works as expected.

my $delimiters = '/:| |%|*|$||!|#|&|^|_|-|,|./';
my test = ("thaddeus Cooper ",
            "%idiotic_Field*name",
            "hey#hey#Hey,hello_world",
           
"this#is_a_test_of_the-emergency-broadcast-system"
);

foreach my $item (test) {
   $item =~ s/
|%|*|$||!|#|&|^|_|-|,|.)(w)/ucfirst($2)/eg;
   print "$itemn";
}

Result:
D: Perl>pascalcase.pl
ThaddeusCooper
IdioticFieldName
HeyHeyHeyHelloWorld
ThisIsATestOfTheEmergencyBroadcastSystem

Thanks, Mike...
_______________________________________________
ActiveTcl mailing list
ActiveTcllistserv.ActiveState.com
To unsubscribe: http:/
/listserv.ActiveState.com/mailman/mysubs

[1]

about | contact  Other archives ( Real Estate discussion Medical topics )