Luke
Luke

Reputation: 467

Perl regular expression letter.number

Perl

I have strings:

xxxx.log, log.1, log.2, blog, photolog

So I would like to match only the strings named

  1. [log.num] e.g log.1 log.12 log.3
  2. [.log] e.g xxxx.log

not include the string named blog, phtotlog.

any helps would be appreciated.

So far this is my code but i will match blog and some words have "log" that is not i want.

while( <> ) {
        printf "%s",$_ if /log/;
}

Upvotes: 1

Views: 159

Answers (2)

zdim
zdim

Reputation: 66873

As explained, \blog\b may work for your data. However, if log can come in the string along yet other non-word characters (like log-a.txt) that gets matched, too, so you need be more specific. One way is to match precisely what is expected. By the shown sample

while (<>) {
    print if /(?: \.log | log\.\d+ )$/x;
}

where (?: ) is the non capturing group, used so that either of the alternation patterns is anchored to the end of the string, $ (but not needlessly captured). Otherwise we'd match x.log.OLD or such. With the /x modifier spaces may be used without being matched, good for readability.

The patterns in alternation | can be combined but that gets far more complicated.

The printf %s, $var has no advantage over print $var (unless the format is more involved).

A one-liner test

perl -wE'
   @ary = qw(log-out xxxx.log log.1 log.2 blog photolog);
   /(?:\.log|log\.\d+)$/ && say for @ary
'

where feature say is used for the newline, needed here. In a one-liner -E (capital) enables it.

Upvotes: 1

sniperd
sniperd

Reputation: 5274

This should do the trick:

while( <> ) {
        printf "%s",$_ if /\blog\b/;
}

The key being the \b that's a word boundary. You can read about them here: http://www.regular-expressions.info/wordboundaries.html but pretty much it's a space, non letter, the beginning of the line, or end of the line. Another option would be:

/\.log\d/

That would match .log3 The period has to be escaped and the \d means a number. That being said I think \b is what you want.

Upvotes: 0

Related Questions