Regular Expression in TCL

Command: regexp [ options ] pattern str [ matchVar ] [ subVar1 subVar2 ... ]

Options: -nocase, -all, -indices
Command returns number of matches in string.
String is checked from L-R, and by default check stops after encountering first match.

if -all is used: pattern scanning doesn't stop after first match, but continues globally till the end of string.
matchVar is a user defined variable and by default stores the last matched sub-string.
if -indices is used: matchVar stores starting and ending index of pattern matched in string.

Example:
% puts [regexp {t.l} "Welcome to tcl class, tcl is fun" var1 ]
1
% puts $var1
tcl

% puts [regexp -all {t.l} "Welcome to tcl class, tcl is fun" var1 ]
2
% puts $var1
tcl
% regexp -all -indices {t.l} "Welcome to tcl class, tcl is fun" var1 
% puts $var1
22 24

% puts [regexp -all {t.+l} "Welcome to tcl class, tcl is fun" var1 ]
2
% puts $var1
to tcl class, tcl 


Pattern grouping:
This is where subVar's come into picture.
You can group a part of string and store it in variables.
Done using parenthesis.

Example:
## To store first 2 words in variables name & surname. The parenthesis indicates grouping of patterns.
% regexp {(\w+) (\w+) .*} "MS Dhoni is the best finisher in cricket." var1 name surname 
% puts $var1
MS Dhoni is the best finisher in cricket.
% puts $name
MS
% puts $surname
Dhoni


Substitutions in Regular Expressions:
Command: regsub [ options ] pattern str replacement_str [ matchVar ]

Options: -all, -nocase
Returns number of replacements.
Original string is not modified.

-all and -nocase options work similar to their description in regexp command options.

If pattern is found in str, that sub-string will be replaced by replacement_str.

Example:
% puts [regsub  {perl} "Welcome to perl class, perl is fun" "tcl" var1]
1
% puts $var1
Welcome to tcl class, perl is fun

% puts [regsub  -all {perl} "Welcome to perl class, perl is fun" "tcl" var1]
1
% puts $var1
Welcome to tcl class, tcl is fun



Comments

Popular posts from this blog

The struggle to enter VLSI industry is for real

What should you expect in an VLSI interview as a fresher