[ale] [OT] Regular Expression Help

Brandon Checketts brandon at brandonchecketts.com
Tue Aug 25 12:44:39 EDT 2009


I don't know that there is a way to do it with just a regular expression (ie:
sed).  It is pretty trivial to do in Perl.  This seems to do what you want:

#!/usr/bin/perl

open(HANDLE, 'file');
while(<HANDLE>) {
    if (/^\s*(\d*)\s*\d*\s*(\w*)\s*\d+\:\d+/) {
        print "line $1 = ";
        print $2 || 'n';
        print "\n";
    }
}

Somebody could probably shorten that to a single line.....

Output:
[root at dev tmp]# perl test.pl
line 1 = n
line 2 = U
line 3 = O
line 4 = n
line 5 = n
line 6 = T



Thanks,
Brandon Checketts


Calvin Harrigan wrote:
> Hi guys, I really hate having to bring up something so off topic, but I 
> need a little help with regular expressions.
> I have the following strings that I need to extract the optional letter 
> after the second number.
> 
>      1    115       8:20
> 
>      2    113 U     8:21
> 
>      3    119 O     8:22
> 
>      4    115       8:26
> 
>      5    115       8:26
> 
>      6    115 T     8:27
> 
> line 2  = 'U'
> line 3  = 'O'
> line 4  = ''
> 
> I have the this expression, which does what I need it to:
> 
> ^\s*\d*\s*\d*\s*(?<WeightMod>\w*)\s*\d+\:\d+
> 
> It extracts the letters just fine. For the lines that there isn't a 
> letter, it returns an empty string, which is expected.
> Is there any way to substitute another string when there is no letter to 
> be captured?
> 
> i.e;
> line 4 = 'N'
> 
>    I've been looking for a solution since yesterday, can't quite seem to 
> pin it down.
> 
> 
> Thanks
> _______________________________________________
> Ale mailing list
> Ale at ale.org
> http://mail.ale.org/mailman/listinfo/ale



More information about the Ale mailing list