简体   繁体   中英

Can I use a full word to split on a string?

This may be a simpleton question. I have a string that is consistent with the content. It will contain the word "IMAGE" . I want to be able to split on this word so I get the content after the word. I tried:

my @sname = split('IMAGE', $fshare);

$fshare contains a string such as '\\\\Disk\\InfoIMAGEstuff' . I want the 'stuff' part.

The first argument to split is a regex pattern, not a string. You can pass a third argument as a limit to prevent it from splitting into more than 2 strings (more than once).

my ($before, $after) = split /IMAGE/, $fshare, 2;

If the string you want to split on contains regex metacharacters, you will want to use \\Q so the string is interpreted literally.

my ($before, $after) = split /\Qfoo.bar/, $fshare, 2;

If you only care about what is after the delimiter, you can use a simple regex capture to retrieve this.

my ($after) = $fshare =~ m/IMAGE(.*)/s;

The /s modifier allows . to additionally match newlines.

If you just want to get the part after the string, you could avoid using split (and the RegEx engine) all together and use string ops instead.

my $string = '\\Disk\InfoIMAGEstuff';
my $delim  = 'IMAGE';
my $post   = substr($string, index($string, $delim) + length($delim));

It's not super pretty, but it benchmarks twice as fast as using split . Even though we are calling 3 functions ( substr , index , and length ), string ops like these are incredibly fast.

In this example, index matches the first occurrence of $delim . If you want to match the last occurrence, use rindex instead.

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