Extract substring using two delimiters and NO REGEX

mac tíre beag Source

I have a function whose aim is to extract a substring found between two delimiters. I would use regex but in this case I have explicit instructions not to use them.

I had a simpler and more elegant solution which was just one line but I cannot for the life of me remember or find it.

sub findBetween {

my ($theString,$delimiter1,$delimiter2) = (@_);
my $tmp = substr($theString, index($theString,$delimiter1)+length($delimiter1));
$tmp = substr($tmp, 0, index($tmp,$delimiter2));
return $tmp;}

Thank you for taking a look at this issue, I am aware it is very basic and somewhat redundant. What I need is a simpler solution involving perl basic functions and no regex.



answered 3 months ago Gerhard Barnard #1

I would simply use index

use strict;
use warnings;

my $string = "hello my world";
my $substr = "my";
    if (index($string, $substr) != -1) {
        print "$substr found in $string";

Extract from perldoc


• index STR,SUBSTR

The index function searches for one string within another, but without the wildcard-like behavior of a full regular-expression pattern match. It returns the position of the first occurrence of SUBSTR in STR at or after POSITION. If POSITION is omitted, starts searching from the beginning of the string. POSITION before the beginning of the string or after its end is treated as if it were the beginning or the end, respectively. POSITION and the return value are based at zero. If the substring is not found, index returns -1.

answered 3 months ago Сухой27 #2

You can use two index() calls to locate both delimiters and use indexes to extract string between them,

sub findBetween {

    my ($theString,$delimiter1,$delimiter2) = @_;

    my $i1 = index($theString, $delimiter1, 0) + length($delimiter1);
    my $i2 = index($theString, $delimiter2, $i1);

    return substr($theString, $i1, $i2-$i1);

print findBetween("111--2222~~333", "--", "~~"), "\n";



comments powered by Disqus