简体   繁体   中英

perl how to remove last '_'?

In perl, how to write this regex ?

my $line = "job_name_1_" ; #end with '_'

$pattern = "_$"; # tried "\_$", still doesn't work

if($line =~ m/$pattern/){
    # remove last "_" ?
}

-#output should be "job_name"

how to do this ?

要删除最后一个下划线字符,您只需要执行以下操作:

$line =~ s/_$//;
$subject =~ s/_(?=[^_]*$)//;

对不起,如果其他人也发布了这个:)

To remove a trailing underscore: ( foo__foo_ , foo_barfoo_bar )

$line =~ s/_\z//;

To remove all trailing underscores: ( foo__foo , foo_barfoo_bar )

$line =~ s/_+\z//;

To remove the last underscore: ( foo__foo_ , foo_barfoobar )

$line =~ s/_(?!.*_)//s;

$line =~ s/^.*\K_//s;

Try this:

$test = "test_";
$test = $1 if($test=~/(.*)_$/);
print $test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM