algorithm - Perl: Transfer substring positions between two strings -
i'm writing perl programm , i've got following problem: have large list of start , end positions in string. positions correspond substrings in string. want transfer positions second string. second string identical first string, except has additional hyphen.
example original string: "abcdef" , 1 substring "bcde"
what have:
- positions of substring in original string: start = 1, end = 4
- the original string additional hyphen: "-ab---cd--e-f---"
what want:
- position of substring in hyphen-string: start=2, end=10
i have large list of substring positions.
i suspect have shown reduced version of problem, in case solution may not work real situation.
however, seems simplest build regex interspersing -*
(i.e. 0 or more hyphens) between characters.
this program works way, building regex of b-*c-*d-*e
, comparing both of sample strings.
use strict; use warnings; @strings = qw/ abcdef -ab---cd--e-f--- /; ($start, $end) = (1, 4); $substr = substr $strings[0], $start, $end-$start + 1; $regex = join '-*', split //, $substr; $regex = qr/$regex/; $string (@strings) { if ($string =~ $regex) { printf "substring found @ %d %d in string %s\n", $-[0], $+[0]-1, $string; } }
output
substring found @ 1 4 in string abcdef substring found @ 2 10 in string -ab---cd--e-f---
Comments
Post a Comment