Regex,regsub :
A
regular expression is simply a description of a pattern that describes a set of possible characters in an input string.
Example :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#I want to replace dog with cat in the following statement | |
set exp1 "someone let the dog out of bag" | |
#First check whether dog is present in bag or not | |
set val [regexp (dog) $exp1 sub1 sub2 sub3] | |
puts $sub1 | |
if { $val } { | |
regsub dog $exp1 cat exp2 | |
} | |
puts "original expression : $exp1" | |
puts "modified expression : $exp2" | |
set exp3 "I have one black dog, one white dog and one brown dog in my bag" | |
#replace all dogs with corresponding cats | |
regsub -all dog $exp3 cat exp4 | |
puts $exp4 | |
#When you don't want to include particular pattern in sub-pattern use ?: | |
set exp5 "Sasken LSI TI Mirafra" | |
regexp "(Sasken|Smartplay).*(?:LSI|Avago).*(Mirafra)" $exp5 sub1 sub2 sub3 | |
#Output : | |
#% puts $sub1 | |
#Sasken LSI TI Mirafra | |
#% puts $sub2 | |
#Sasken | |
#% puts $sub3 | |
#Mirafra | |
set exp6 "Ooh La La Tu Hai Meri Fantasy " | |
regexp -nocase (oo)? $exp6 sub1 | |
puts $sub1 | |
#If I want to search starting with ^O and ending with y | |
regexp "^O.*y$" $exp6 | |
#Loop through all the words in the exp6 and put the words which doesn't start with vowels | |
foreach var $exp6 { | |
if { [regexp -nocase {^[^aeiou]} $var ] } { | |
puts $var | |
} | |
} | |
#Output | |
#La | |
#La | |
#Tu | |
#Hai | |
#Meri | |
#Fantasy |
No comments:
Post a Comment