Reputation: 573
I have to parse this format using regexp in TCL. Here is the format
wl -i eth1 country
Q1 (Q1/27) Q1
I'm trying to use the word country as a keyword to parse the format 'Q1 (Q1/27) Q1'. I can do it if it is in a same line as country using the following regexp command.
regexp {([^country]*)country(.*)} $line match test country_value
But how can i tackle the above case?
Upvotes: 0
Views: 365
Reputation: 137567
Firstly, the regular expression you are using isn't doing quite the right thing in the first place, because [^country]
matches a set of characters that consists of everything except the letters in country
(so it matches from the h
in eth1
onwards only, given the need to have country
afterwards).
By default, Tcl uses the whole string to match against and newlines are just ordinary characters. (There is an option to make them special by also specifying -line
, but it's not on by default.) This means that if I use your whole string and feed it through regexp
with your regular expression, it works (well, you probably want to string trim $country_value
at some point). This means that your real problem is in presenting the right string to match against.
If you're presenting lines one at a time (read from a file, perhaps) and you want to use a match against one line to trigger processing in the next, you need some processing outside the regular expression match:
set found_country 0
while {[gets $channel line] >= 0} {
if {$found_country} {
# Process the data...
puts "post-country data is $line"
# Reset the flag
set found_country 0
} elseif {[regexp {(.*) country$} $line -> leading_bits]} {
# Process some leading data...
puts "pre-country data is $leading_bits"
# Set the flag to handle the next line specially
set found_country 1
}
}
If you want to skip blank lines completely, put a if {$line eq ""} continue
before the if {$found_country} ...
.
Upvotes: 2