The quantifier follows nothing in the regular expression

My requirement is to print files with the text 'xyz' in the file names using perl . I tried below and got the following error:

The quantifier does not follow anything in the regular expression labeled <- HERE in m / * <- HERE xyz.xlsx $ /;

use strict; use warnings; my @files = qw(file_xyz.xlsx,file.xlsx); my @my_files = grep { /*xyz.xlsx$/ } @files; for my $file (@my_files) { print "The output $file \n"; } 

The problem occurs when I add * to the grep regular expression. How can i achieve this?

+6
source share
1 answer

* - a metacharacter called a quantifier. This means "repeat the previous character or character class zero or more times." In your case, this does not mean anything, and therefore is a syntax error. You are probably trying to match anything that is .* : Wildcard followed by a quantifier. However, this is already the default behavior for a regular expression if it is not bound. So all you need is:

 my @my_files = grep { /xyz/ } @files; 

You can save the end of the xlsx$ line binding, but since you have a limited list of file names, this is hardly necessary. Although you used qw() incorrectly, it is not separated by a comma, this space is divided:

 my @files = qw(file_xyz.xlsx file.xlsx); 

However, if you should have a larger set of file names, for example, one from a directory reading, you can put a wildcard in the middle:

 my @my_files = grep { /xyz.*\.xlsx$/i } @files; 

Note the use of the /i modifier to make case insensitive. Also note that you must exit . because it is another metacharacter.

+6
source

Source: https://habr.com/ru/post/949986/


All Articles