"Daniel Völkerts" <dvoelkerts@web.de> schrieb im Newsbeitrag
news:cfr4ml$d13$00$1@news.t-online.com...
Robert Klemme wrote:
> Some more admittedly ugly constructions:
>
> val = "<165> Aug 16 17:01:35 localhost Just a test"
(1) This one converts the RX MatchData into an array and tests for emptyness
to determine whether it matched. And along the way values are assigned to
local vars.
> unless ( ( pri, timestamp, device, msg = * /^<(\d+)> \s+ (\S+ \s+ \d+
\s+
> \d+:\d+:\d+) \s+ (\S+) \s+ (.*)$/x.match(val).to_a ).empty? )
> puts "matched"
> end
(2) Similar, but now just one local var is used as match check: if "pri" is
not nil, the RX matched.
> pri, timestamp, device, msg = * /^<(\d+)> \s+ (\S+ \s+ \d+ \s+
\d+:\d+:\d+)
> \s+ (\S+) \s+ (.*)$/x.match(val).to_a
> if pri
> puts "matched"
> end
(3) Same approach as (1) but the regexp is defined as a constant to make
stuff more readable.
> LOG_RX = /^<(\d+)> \s+ (\S+ \s+ \d+ \s+ \d+:\d+:\d+) \s+ (\S+) \s+
(.*)$/x
>
> unless ( ( pri, timestamp, device, msg = *
LOG_RX.match(val).to_a ).empty? )
> puts "matched"
> end
(4) Similar approach to (2) but the test is included ("&& line"). Note that
this time no conversion to array is done here so we need the additional
local "line" to receive the complete capture.
> if ( line, pri, timestamp, device, msg = * /^<(\d+)> \s+ (\S+ \s+ \d+
\s+
> \d+:\d+:\d+) \s+ (\S+) \s+ (.*)$/x.match(val) ) && line
> puts "matched"
> end
(5) Same as (4) but with regexp in constant as in (3).
> if ( line, pri, timestamp, device, msg = * LOG_RX.match(val) ) && line
> puts "matched"
> end
>
> 
>
> robert
>
*boom* That blow my mind away! No no, thanks a lot for that piece of code.
I *should've* put some comments in... Ok, inserting them above now.
But I prefer the scanf and one-line-regexp.
Basically I used extended regular expressions (switched by the "/x" flag).
Whitespace is ignored, that's why you see more "\s+" in there. And that's
why the regexp is longer.
I'll test which kind performs better for my needs. As I said, I'm a ruby
newbie and personal programming rule is: keep it simple!
I've to
understand the things I wrote.
That's an excellent road to walk down! Handcrafted, simple code is better
than a mindless copy of something found somewhere.
Kind regards
robert