Reputation: 11
I'm trying to extract strings from a file that match the following format:
AP[1st nibble].[2nd nibble].[3rd nibble]
For example: AP30f7.0df6.e51c
The code below captures all data sharing the same line as the above string. What can I do to stop capturing any undesired data found on the same line as the above string?
while { [gets $fchan inline] >= 0} {
switch -regexp -- $inline {
AP([a-f0-9]{4}\.[a-f0-9]{4}\.[a-f0-9]{4}) {
append default_name $inline\n
}
}
}
UPDATE:
Found a work around. Since each line matching the condition I've specified starts with the desired string, I'll use the string range command to extract only the first 16 characters.
while { [gets $fchan inline] >= 0} {
switch -regexp -- $inline {
AP([a-f0-9]{4}\.[a-f0-9]{4}\.[a-f0-9]{4}) {
set inline_mod [string range $inline 0 15]
append default_name $inline_mod\n
}
}
}
Upvotes: 0
Views: 607
Reputation: 137587
The switch
command has some useful options when you want to do extraction at the same time as matching an RE. In particular, you should use the -matchvar
option.
while { [gets $fchan inline] >= 0} {
switch -regexp -matchvar matched -- $inline {
AP([a-f0-9]{4}\.[a-f0-9]{4}\.[a-f0-9]{4}) {
# Extract the first and second elements
lassign $matched inline_mod triple
# With your sample of AP30f7.0df6.e51c
# $inline_mod is "AP30f7.0df6.e51c"
# $triple is "30f7.0df6.e51c"
append default_name $inline_mod\n
}
}
}
There are some further examples on that manual page.
Upvotes: 1